user647527 user647527 - 1 year ago 105
JSON Question

How to retrieve data from golang-map

I put my json data on Unmarsha1. How can i retrieve data like


but how can I retrieve data like
log.Print(b["beat"]["name"]) --> fail to get data

My Code is like following:

var b map[string]interface{}

data := []byte(`

err := json.Unmarshal(data, &b)

if err != nil{
fmt.Println("error: ", err)

Thank You

Answer Source

you got error cause b["beat"] is not a map, so you can't use b["beat"]["name"].

you declare b with map[string]interface{}, so b can use like b["beat"],but b["beat"] is a value of interface type, so it can use like b["beat"]["name"], for this you can add these line.

var m map[string]interface{}
m = b["beat"].(map[string]interface{})

it turn type for b["beat"] from interface to map.

For more:

  1. you can create a struct for this json string,and then you can get value from your struct with . symbol. like the Unmarshal exsample in

  2. there is a package go-simplejson can get json value easily.

Hope this can help you...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download