dou11655853 2014-08-23 19:20
浏览 95
已采纳

Golang将JSON数组解析为数据结构

I am trying to parse a file which contains JSON data:

[
  {"a" : "1"},
  {"b" : "2"},
  {"c" : "3"}
]

Since this is a JSON array with dynamic keys, I thought I could use:

type data map[string]string

However, I cannot parse the file using a map:

c, _ := ioutil.ReadFile("c")
dec := json.NewDecoder(bytes.NewReader(c))
var d data
dec.Decode(&d)


json: cannot unmarshal array into Go value of type main.data

What would be the most simple way to parse a file containing a JSON data is an array (only string to string types) into a Go struct?

EDIT: To further elaborate on the accepted answer -- it's true that my JSON is an array of maps. To make my code work, the file should contain:

{
  "a":"1",
  "b":"2",
  "c":"3"
}

Then it can be read into a map[string]string

  • 写回答

3条回答 默认 最新

  • dsxay48646 2014-08-23 20:18
    关注

    It's because your json is actually an array of maps, but you're trying to unmarshall into just a map. Try using the following:

    type YourJson struct {
        YourSample []struct {
            data map[string]string
        } 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line