Home > Blockchain >  golang recursive json to struct?
golang recursive json to struct?

Time:01-15

I used to write python, just started to contact golang

my json for example,children unknow numbers,may be three ,may be ten。

[{
    "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?

CodePudding user response:

You can reuse the AutoGenerated type in its definition:

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.)

Output (try it on the Go Playground):

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

Also it's easier to understand and work with if AutoGenerated itself is not a slice:

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.

  • Related