How to Handle JSON with Nested Objects in Go

Unmarshal nested JSON in Go by defining a struct with sub-struct fields and using json.Unmarshal.

Use the encoding/json package to unmarshal JSON into a struct with nested fields defined as sub-structs. Define your struct to match the JSON hierarchy, then call json.Unmarshal with the byte slice and a pointer to your struct instance.

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Address struct {
	City  string `json:"city"`
	State string `json:"state"`
}

type Person struct {
	Name    string  `json:"name"`
	Address Address `json:"address"`
}

func main() {
	jsonData := []byte(`{"name":"Alice","address":{"city":"NYC","state":"NY"}}`)
	var p Person
	if err := json.Unmarshal(jsonData, &p); err != nil {
		log.Fatal(err)
	}
	fmt.Println(p.Name, p.Address.City)
}