Reputation: 30132
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
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