Home  >  Article  >  Backend Development  >  golang recursive json to struct?

golang recursive json to struct?

WBOY
WBOYforward
2024-02-05 23:27:07608browse

golang recursive json to struct?

Question content

I have written python before, but I just started to get in touch with golang

Take my json as an example. The child does not know the number. It may be three or ten.

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

I write the structure

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 is stupid. How to optimize?


Correct Answer


You can reuse it in its definition autogenerate Type:

type autogenerated []struct {
    id       int           `json:"id"`
    name     string        `json:"name"`
    children autogenerated `json:"children"`
}

Test it:

var o autogenerated

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

fmt.println(o)

(src is your json input string.)

Output (try on go playground):

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

It is easier to understand and use if autogenerate is not a slice itself:

type autogenerated struct {
    id       int             `json:"id"`
    name     string          `json:"name"`
    children []autogenerated `json:"children"`
}

Then use it/test it:

var o []AutoGenerated

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

fmt.Println(o)

The output is the same. Try this on go playground.

The above is the detailed content of golang recursive json to struct?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete