在Go语言中解析多层次的JSON文件。

huangapple go评论90阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年12月31日 14:46:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/27717314.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定