Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang recursive json to struct?

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?

like image 600
xin.chen Avatar asked Mar 18 '26 04:03

xin.chen


1 Answers

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.

like image 77
icza Avatar answered Mar 20 '26 22:03

icza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!