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 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!