Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access deeply nested json keys and values

Tags:

go

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?

like image 544
ojosilva Avatar asked May 21 '13 15:05

ojosilva


1 Answers

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)
like image 164
Codefor Avatar answered Sep 30 '22 19:09

Codefor