how to access deeply nested json keys and values

后端 未结 2 1210
离开以前
离开以前 2021-01-18 08:12

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\"

相关标签:
2条回答
  • 2021-01-18 08:31

    You may like to consider the package github.com/bitly/go-simplejson

    See the doc: http://godoc.org/github.com/bitly/go-simplejson

    Example:

    time, err := json.Get("args").GetIndex(0).String("time")
    if err != nil {
        panic(err)
    }
    log.Println(time)
    
    0 讨论(0)
  • 2021-01-18 08:38

    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

    0 讨论(0)
提交回复
热议问题