英文:
How to retrieve data from golang-map
问题
我将我的JSON数据放在Unmarshal中。如何像这样检索数据:
log.Print(b["beat"]["name"])
但是,如何检索像这样的数据:
log.Print(b["beat"]["name"]) --> 无法获取数据
我的代码如下:
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"])
谢谢。
英文:
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
答案1
得分: 1
你因为b["beat"]不是一个映射而出现了错误,所以不能使用b["beat"]["name"]。
你用map[string]interface{}声明了b,所以可以像b["beat"]这样使用,但是b["beat"]是一个接口类型的值,所以不能像b["beat"]["name"]这样使用,你可以添加以下代码:
var m map[string]interface{}
m = b["beat"].(map[string]interface{})
log.Println(m["name"])
这将把b["beat"]的类型从接口转换为映射。
更多信息:
- 
你可以为这个JSON字符串创建一个结构体,然后可以使用
.符号从结构体中获取值。可以参考https://www.dotnetperls.com/json-go中的Unmarshal示例。 - 
有一个名为go-simplejson的包可以轻松获取JSON值。
 
希望这能帮到你...
英文:
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:
- 
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 - 
there is a package go-simplejson can get json value easily.
 
Hope this can help you...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论