go - Traversing a Golang Map -
i initialized variable named data this:
var data interface{}
then unmarshalled raw json into.
err = json.unmarshal(raw, &data)
i've run these 2 functions on it:
fmt.println(reflect.typeof(data)) fmt.println(data)
and return this:
map[string]interface {} map[tasks:[map[payload:map[key:36a6d454-feee-46eb-9d64-a85abeabbcb7] code_name:image_resize]]]
and need access "key". have tried these approaches , few more:
data["tasks"][0]["payload"]["key"] data[0][0][0][0]
those have given me error similar one:
./resize.go:44: invalid operation: data["tasks"] (index of type interface {})
any advice on how grab "key" value out of interface? in advance.
since know schema, best way unmarshal directly structs can use.
http://play.golang.org/p/ainzp8izqa
package main import ( "encoding/json" "fmt" ) type msg struct { tasks []task `json:"tasks"` } type task struct { codename string `json:"code_name"` payload payload `json:"payload"` } type payload struct { key string `json:"key"` } func main() { var data msg raw := `{ "tasks": [ { "code_name": "image_resize", "payload": { "key": "36a6d454-feee-46eb-9d64-a85abeabbcb7" } } ] }` err := json.unmarshal([]byte(raw), &data) if err != nil { fmt.println(err) return } fmt.println(data.tasks[0].payload.key) }
if insist on doing things hard way using original code, need type assertions. highly recommend avoiding route when possible. not fun. every step needs checked ensure matches data structure expect.
http://play.golang.org/p/fi5sqkv19j
if m, ok := data.(map[string]interface{}); ok { if a, ok := m["tasks"].([]interface{}); ok && len(a) > 0 { if e, ok := a[0].(map[string]interface{}); ok { if p, ok := e["payload"].(map[string]interface{}); ok { if k, ok := p["key"].(string); ok { fmt.println("the key is:", k) } } } } }
in response goodwine's question: can read further how marshal , unmarshal reading encoding/json godoc. suggest starting here:
Comments
Post a Comment