gpt4 book ai didi

go - 如何访问深度嵌套的 json 键和值

转载 作者:IT王子 更新时间:2023-10-29 00:34:26 25 4
gpt4 key购买 nike

我正在用 Go 编写一个 websocket 客户端。我从服务器收到以下 JSON:

{"args":[{"time":"2013-05-21 16:57:17"}],"name":"send:time"}

我正在尝试访问 time 参数,但无法掌握如何深入到接口(interface)类型:

 package main;
import "encoding/json"
import "log"
func main() {
msg := `{"args":[{"time":"2013-05-21 16:56:16", "tzs":[{"name":"GMT"}]}],"name":"send:time"}`
u := map[string]interface{}{}
err := json.Unmarshal([]byte(msg), &u)
if err != nil {
panic(err)
}
args := u["args"]
log.Println( args[0]["time"] ) // invalid notation...
}

这显然是错误的,因为符号不正确:

   invalid operation: args[0] (index of type interface {})

我只是找不到一种方法来深入 map 以获取深层嵌套的键和值。

一旦我不再抓取动态值,我想声明这些消息。我将如何编写类型结构来表示如此复杂的数据结构?

最佳答案

您可能会考虑包裹 github.com/bitly/go-simplejson

查看文档:http://godoc.org/github.com/bitly/go-simplejson

例子:

time, err := json.Get("args").GetIndex(0).String("time")
if err != nil {
panic(err)
}
log.Println(time)

关于go - 如何访问深度嵌套的 json 键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16674059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com