user647527 user647527 - 1 month ago 10
JSON Question

How to retrieve data from golang-map

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

log.Print(b["beat"]["name"])


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(`
{"foo":1,"beat":{"@timestamp":"2016-10-27T12:02:00.352Z","name":"localhost.localdomain","version":"6.0.0-alpha1"}}
`)

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

if err != nil{
fmt.Println("error: ", err)
}
log.Print(b)
log.Print(b["beat"]["name"])


Thank You

Answer

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{})
log.Println(m["name"])

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 https://www.dotnetperls.com/json-go

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

Hope this can help you...

Comments