How to access deeply nested json keys and values

I am writing a websocket client in Go. I get the following JSON from the server:

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

I am trying to access the time parameter, but just can't figure out how to penetrate deep into the 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 are obviously errors, since the notation is incorrect:

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

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

As soon as I can intercept dynamic values, I would like to declare these messages. How to write a type structure to represent such complex data structures?

+4
go
May 21 '13 at 15:42
source share
2 answers

The part of the interface{} map[string]interface{} that you are decoding will match the type of this 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 JSON structure, you should try to determine the structure that matches this structure and cancel it. Example:

 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) 

This may not be perfect, but should give you an idea.

+7
May 21 '13 at 16:13
source share

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

See document: 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) 
+8
May 22 '13 at 15:47
source share



All Articles