Raghav Hinduja Switzerland (Swiss) - How do I handle JSON unmarshalling for nested structs?

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 int json:"id"
Name string json:"name"
Customer Customer json:"customer"
}

type Customer struct {
	ID    int    `json:"id"`
	Email string `json:"email"`
}

then :
var order Order
err := json.Unmarshal(data, &order)

1 Like

Yeah - I recommend Matt Holt’s json to go tool if you have JSON and want to product a corresponding struct:

1 Like