首页 > 后端开发 > Golang > 正文

如何在不使用自定义编组器和解组器的情况下访问 Go 中深度嵌套的 JSON 键和值?

DDD
发布: 2024-10-26 19:41:02
原创
411 人浏览过

How can I access deeply nested JSON keys and values in Go without using custom marshalers and unmarshalers?

在 Go 中访问深度嵌套的 JSON 键和值

考虑以下用 Go 编写的 websocket 客户端代码:

import (
    "encoding/json"
    "log"
)

func main() {
    msg := `{"args":[{"time":"2013-05-21 16:56:16", "tzs":[{"name":"GMT"}]}],"name":"send:time"}`
    var u map[string]interface{}

    err := json.Unmarshal([]byte(msg), &u)
    if err != nil {
        log.Fatalf("Failed to unmarshal: %v\n", err)
    }

    args := u["args"]

    // Attempting to directly access the time key will throw an error
    log.Println(args[0]["time"]) // invalid notation
}
登录后复制

在这种情况下,由于访问深度嵌套的“time”键时的表示法不正确,会出现“无效操作:args[0] (index of type interface {})”错误。

解决方案

推荐的解决方案涉及利用 github.com/bitly/go-simplejson 包,它简化了 JSON 数据结构的导航。详细信息请参阅 http://godoc.org/github.com/bitly/go-simplejson 的文档。

将此包应用于上述代码:

// Import go-simplejson
import "github.com/bitly/go-simplejson"

func main() {
    // Create a JSON object
    json := simplejson.New()
    json.Decode([]byte(msg))

    // Using go-simplejson, access the time key
    time, err := json.Get("args").GetIndex(0).String("time")
    if err != nil {
        log.Fatalf("Failed to get time: %v\n", err)
    }

    log.Println(time) // Returns the time value
}
登录后复制

关于原始问题的第二部分,声明 Go 结构体需要自定义编组器和解组器,其中涉及实现encoding.TextMarshaler 和encoding.TextUnmarshaler 接口。然而,使用像 go-simplejson 这样的 JSON 库可以简化这个过程。

以上是如何在不使用自定义编组器和解组器的情况下访问 Go 中深度嵌套的 JSON 键和值?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!