Hi,
I am Raghav Hinduja, a Switzerland-based IT professional. Can anyone explain How to handle JSON unmarshalling for nested structs?
Thanks, Regards
Raghav Hinduja
Hi,
I am Raghav Hinduja, a Switzerland-based IT professional. Can anyone explain How to handle JSON unmarshalling for nested structs?
Thanks, Regards
Raghav Hinduja
You need only lining up your Go struct definitions with the JSON shape
Ex:
{
“id”: 123,
“name”: “Order #1”,
“customer”: {
“id”: 01,
“email”: “user@example.com”
}
}
In Go
type Order struct {
ID intjson:"id"
Name stringjson:"name"
Customer Customerjson:"customer"
}
type Customer struct {
ID int `json:"id"`
Email string `json:"email"`
}
then :
var order Order
err := json.Unmarshal(data, &order)
Yeah - I recommend Matt Holt’s json to go tool if you have JSON and want to product a corresponding struct: