Golang将JSON数组解析为数据结构 [英] Golang parse JSON array into data structure

查看:725
本文介绍了Golang将JSON数组解析为数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析包含JSON数据的文件:

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

 


code> type data map [string] string

然而,我无法使用 map

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


json:无法将数组解析为Go类型main.data的值

什么是最简单的方法解析一个包含JSON数据的文件是一个数组(仅字符串到字符串类型)到一个Go结构?



编辑:为了进一步阐述在接受的答案 - 我的JSON是一个地图数组是真的。为了使我的代码正常工作,文件应该包含:

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

然后它可以被读入 map [string] string

解决方案这是因为你的json实际上是一个地图数组,但你试图解开 map 。尝试使用以下内容:

 类型YourJson结构{
YourSample [] struct {
data map [string ] string
}
}


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

解决方案

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

这篇关于Golang将JSON数组解析为数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆