dongxuanchao1425 2013-05-21 15:42
浏览 39
已采纳

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

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?

  • 写回答

2条回答 默认 最新

  • dongmi0760 2013-05-21 16:13
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题