英文:
Unable to parse JSON array in Golang
问题
我正在努力解析以下JSON数组。
// JSON数组
[
{
"ShaId": "adf56a4d",
"Regions": [
{
"Name": "us-east-1a"
}
]
}
.... 更多类似的
]
Go Playground链接:https://play.golang.org/p/D4VrX3uoE8
我在哪里犯了错误?
英文:
I am having hard time parsing following JSON array.
// JSON Array
[
{
"ShaId": "adf56a4d",
"Regions": [
{
"Name": "us-east-1a"
}
]
}
.... more such
]
Link to Go Playground :- https://play.golang.org/p/D4VrX3uoE8
Where am I making mistake?
答案1
得分: 2
这是您的原始JSON输入:
content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}`
它不是一个数组,将其改为:
content := `[{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}]`
使用这个结果:
Results: []main.ShaInfo{main.ShaInfo{ShaId:"adf56a4d",
Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}}
注意:
如果您的输入不是一个数组,则不要尝试从中解析出一个数组(切片),只需一个ShaInfo
。如果您不能修改输入,这也适用:
var data ShaInfo
content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}`
json.Unmarshal([]byte(content), &data)
输出:
Results: main.ShaInfo{ShaId:"adf56a4d",
Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}
英文:
This is your original JSON input:
content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}`
It is not an array, change it to:
content := `[{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}]`
With this, the result:
Results: []main.ShaInfo{main.ShaInfo{ShaId:"adf56a4d",
Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}}
Note:
If you input is not an array, then don't try to parse an array (slice) out of it, just one ShaInfo
. This also works if you don't/can't modify the input:
var data ShaInfo
content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}`
json.Unmarshal([]byte(content), &data)
Output:
Results: main.ShaInfo{ShaId:"adf56a4d",
Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论