duandi5328 2016-10-27 06:39
浏览 116
已采纳

如何从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

  • 写回答

1条回答 默认 最新

  • douwu8060 2016-10-27 07:36
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?