Jacob Marble
Jacob Marble

Reputation: 30132

How to JSON unmarshal a struct in a list in a struct in Go?

How can I deserialize this JSON data into a proper struct within an array/slice within a struct? I would like to avoid deserializing to a map.

d := []byte(`{
    "a": 1,
    "b": [
        {"c": 3, "d": 4},
        {"c": 5, "d": 6}
    ]
    }`)

Upvotes: 0

Views: 115

Answers (1)

Jacob Marble
Jacob Marble

Reputation: 30132

This solution is quite intuitive:

d := []byte(`{
    "a": 1,
    "b": [
        {"c": 3, "d": 4},
        {"c": 5, "d": 6}
    ]
    }`)

var j struct {
    A uint
    B []struct {
        C uint
        D uint
    }
}
if err := json.Unmarshal(d, &j); err != nil {
    log.Fatal(err)
}
fmt.Printf("%+v\n", j)

The result, printed to stdout: {A:1 B:[{C:3 D:4} {C:5 D:6}]}

Upvotes: 3

Related Questions