简体   繁体   English

golang 递归 json 结构?

[英]golang recursive json to struct?

I used to write python, just started to contact golang以前写python,刚开始接触golang

my json for example,children unknow numbers,may be three,may be ten。比如我的json,小朋友不知道数字,可能是三,可能是十。

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

i write struct我写结构

    
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"`
}

but i think this too stupid。 how to optimize?但我觉得这太愚蠢了。如何优化?

You can reuse the AutoGenerated type in its definition:您可以在其定义中重用AutoGenerated类型:

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

Testing it:测试它:

var o AutoGenerated

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

fmt.Println(o)

( src is your JSON input string.) src是您的 JSON 输入字符串。)

Output (try it on the Go Playground ): Output(在Go 游乐场试试):

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

Also it's easier to understand and work with if AutoGenerated itself is not a slice:如果AutoGenerated本身不是切片,也更容易理解和使用:

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

Then using it / testing it:然后使用它/测试它:

var o []AutoGenerated

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

fmt.Println(o)

Outputs the same.输出相同。 Try this one on the Go Playground .Go 游乐场试试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM