golang recursive json to struct?

WBOY
Release: 2024-02-05 23:27:07
forward
554 people have browsed it

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": []
            }]
        }]
    }]
}]
Copy after login

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"`
}
Copy after login

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"`
}
Copy after login

Test it:

var o autogenerated

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

fmt.println(o)
Copy after login

(src is your json input string.)

Output (try on go playground):

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

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"`
}
Copy after login

Then use it/test it:

var o []AutoGenerated

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

fmt.Println(o)
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!