Golang递归JSON到结构?

golang recursive json to struct?

提问人:xin.chen 提问时间:1/14/2023 最后编辑:iczaxin.chen 更新时间:1/14/2023 访问量:140

问:

我曾经写过python,刚开始接触golang

以我的JSON为例,孩子不知道数字,可能是三个,可能是十个。

[{
    "id": 1,
    "name": "aaa",
    "children": [{
        "id": 2,
        "name": "bbb",
        "children": [{
            "id": 3,
            "name": "ccc",
            "children": [{
                "id": 4,
                "name": "ddd",
                "children": []
            }]
        }]
    }]
}]

我写结构体

    
type AutoGenerated []struct {
    ID       int    `json:"id"`
    Name     string `json:"name"`
    Children []struct {
        ID       int    `json:"id"`
        Name     string `json:"name"`
        Children []struct {
            ID       int    `json:"id"`
            Name     string `json:"name"`
            Children []struct {
                ID       int           `json:"id"`
                Name     string        `json:"name"`
                Children []interface{} `json:"children"`
            } `json:"children"`
        } `json:"children"`
    } `json:"children"`
}

但我觉得这太傻了。 如何优化?

json go 结构 体切片

评论


答:

3赞 icza 1/14/2023 #1

您可以在其定义中重用该类型:AutoGenerated

type AutoGenerated []struct {
    ID       int           `json:"id"`
    Name     string        `json:"name"`
    Children AutoGenerated `json:"children"`
}

测试它:

var o AutoGenerated

if err := json.Unmarshal([]byte(src), &o); err != nil {
    panic(err)
}

fmt.Println(o)

src 是 JSON 输入字符串。

输出(在 Go Playground 上尝试):

[{1 aaa [{2 bbb [{3 ccc [{4 ddd []}]}]}]}]

此外,如果它本身不是一个切片,它更容易理解和使用:AutoGenerated

type AutoGenerated struct {
    ID       int             `json:"id"`
    Name     string          `json:"name"`
    Children []AutoGenerated `json:"children"`
}

然后使用它/测试它:

var o []AutoGenerated

if err := json.Unmarshal([]byte(src), &o); err != nil {
    panic(err)
}

fmt.Println(o)

输出相同。在 Go Playground 上试试这个。