如何从 Golang 的 map 中检索数据

huangapple go评论74阅读模式
英文:

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"]的类型从接口转换为映射。

更多信息:

  1. 你可以为这个JSON字符串创建一个结构体,然后可以使用.符号从结构体中获取值。可以参考https://www.dotnetperls.com/json-go中的Unmarshal示例。

  2. 有一个名为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:

  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...

huangapple
  • 本文由 发表于 2016年10月27日 14:39:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/40277806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定