How to Marshal and Unmarshal Nested Structs in Go

Convert nested Go structs to JSON bytes using json.Marshal and parse them back using json.Unmarshal.

Use encoding/json.Marshal to convert nested structs to JSON bytes and encoding/json.Unmarshal to parse JSON bytes back into nested struct instances.

package main

import (
	"encoding/json"
	"fmt"
)

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

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

func main() {
	p := Person{Name: "Alice", Address: Address{City: "NYC", State: "NY"}}

	// Marshal: Struct -> []byte
	data, err := json.Marshal(p)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))

	// Unmarshal: []byte -> Struct
	var p2 Person
	err = json.Unmarshal(data, &p2)
	if err != nil {
		panic(err)
	}
	fmt.Println(p2.Name, p2.Address.City)
}