英文:
parsing a multi leve json file in Go Language
问题
我需要解析并从一个JSON文件中获取字段的值。
[{"id": 27}, {"id": 0, "label": "Label 0"}, null, {"id": 93}, {"id": 85}, {"id": 54}, null, {"id": 46, "label": "Label 46"}]}}
虽然我可以处理单层级的JSON,但我不知道如何在这里迭代多层级。
我已经尝试在Google、各种帮助网站甚至Stack Overflow上寻找答案。
我找不到任何可以帮助我处理多层级JSON字节数组的示例。
希望有人能帮助我理解并解决这个问题。
提前感谢。
英文:
I need to parse and get values from fields in a json file.
[{"id": 27}, {"id": 0, "label": "Label 0"}, null, {"id": 93}, {"id": 85}, {"id": 54}, null, {"id": 46, "label": "Label 46"}]}}
Though i can work on single level , i am at a loss how i can iterate through levels here.
I have tried looking for an answer in google , various help sites and even stackoverflow.
I could not find any example that might help me in working with multi level json byte array.
Hope somebody can lead me to understand and work on it.
Thanks in advance
答案1
得分: 4
只需将JSON解析为结构体数组:
package main
import (
"encoding/json"
"fmt"
)
type Item struct {
Id int
Label string
}
func main() {
data := []byte(`[{"id": 27}, {"id": 0, "label": "Label 0"}, null, {"id": 93}, {"id": 85}, {"id": 54}, null, {"id": 46, "label": "Label 46"}]`)
var val []*Item
if err := json.Unmarshal(data, &val); err != nil {
fmt.Printf("Error: %s\n", val)
return
}
for _, it := range val {
fmt.Printf("%#v\n", it)
}
}
希望对你有所帮助。
英文:
Just parse the JSON into an array of structs:
package main
import (
"encoding/json"
"fmt"
)
type Item struct {
Id int
Label string
}
func main() {
data := []byte(`[{"id": 27}, {"id": 0, "label": "Label 0"}, null, {"id": 93}, {"id": 85}, {"id": 54}, null, {"id": 46, "label": "Label 46"}]`)
var val []*Item
if err := json.Unmarshal(data, &val); err != nil {
fmt.Printf("Error: %s\n", val)
return
}
for _, it := range val {
fmt.Printf("%#v\n", it)
}
}
I hope this helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论