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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!