Golang将JSON数组解析为数据结构 [英] Golang parse JSON array into data structure
问题描述
我试图解析包含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屋!
查看全文