如何访问深度嵌套的JSON键和值 [英] how to access deeply nested json keys and values

查看:108
本文介绍了如何访问深度嵌套的JSON键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Go上写了一个websocket客户端。我从服务器接收到以下JSON:



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



我试图访问 time 参数,但是无法掌握如何深入到界面类型中:

  package main; 
importencoding / json
importlog
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])//无效表示法...
}


  $ b 

code>无效操作:args [0](接口类型的索引)

I只是无法找到挖掘地图的方法来抓取深度嵌套的键和值。

一旦我能够抓住动态值,我想宣布这些消息。如何编写一个类型结构来表示这样复杂的数据结构?

interface {} / code>您解码到的 map [string] interface {} 的一部分将匹配该字段的类型。所以在这种情况下:

$ pre $ $ $ $ $ $ )[time]。(string)

应该返回2013- 05-21 16:56:16



然而,如果您知道JSON的结构,您应该尝试定义一个匹配的结构那个结构和解组。例如:

 类型时间结构{
Time time.Time`json:time`
时区[] TZStruct`json:tzs`// obv。您还需要定义TZStruct以及
名称字符串`json:name`
}

类型TimeResponse结构{
Args []时间`json:args `
}

var t TimeResponse
json.Unmarshal(msg,& t)

这可能并不完美,但应该给你这个想法


I'm writing a websocket client in Go. I'm receiving the following JSON from the server:

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

I'm trying to access the time parameter, but just can't grasp how to reach deep into an interface type:

 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...
}

Which obviously errors, since the notation is not right:

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

I just can't find a way to dig into the map to grab deeply nested keys and values.

Once I can get over grabbing dynamic values, I'd like to declare these messages. How would I write a type struct to represent such complex data structs?

解决方案

The interface{} part of the map[string]interface{} you decode into will match the type of that field. So in this case:

args.([]interface{})[0].(map[string]interface{})["time"].(string)

should return "2013-05-21 16:56:16"

However, if you know the structure of the JSON, you should try defining a struct that matches that structure and unmarshal into that. Ex:

type Time struct {
    Time time.Time      `json:"time"`
    Timezone []TZStruct `json:"tzs"` // obv. you need to define TZStruct as well
    Name string         `json:"name"`
}

type TimeResponse struct {
    Args []Time         `json:"args"`
}

var t TimeResponse
json.Unmarshal(msg, &t)

That may not be perfect, but should give you the idea

这篇关于如何访问深度嵌套的JSON键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆