Nested JSON Objects to Nested Go Structs

Convert JSON with nested objects into Go structs with inner struct types. Learn how Go handles hierarchical JSON data with proper type definitions.

Basic Structs

Detailed Explanation

Handling Nested JSON Objects in Go

Real-world JSON almost always contains nested objects. In Go, each nested object becomes its own struct type, and the parent struct holds a field of that type.

Example JSON

{
  "user": {
    "name": "Bob",
    "age": 30,
    "address": {
      "street": "123 Main St",
      "city": "Springfield",
      "zip": "62704"
    }
  }
}

Generated Go Structs

type AutoGenerated struct {
    User User `json:"user"`
}

type User struct {
    Name    string  `json:"name"`
    Age     int     `json:"age"`
    Address Address `json:"address"`
}

type Address struct {
    Street string `json:"street"`
    City   string `json:"city"`
    Zip    string `json:"zip"`
}

How Nesting Works

Go does not support anonymous inline object types like TypeScript does. Every nested JSON object requires a named struct type. The converter generates a separate struct for each level of nesting and names it based on the parent key.

Naming Conventions

When the JSON key is "address", the struct type becomes Address. If there are naming collisions (two different objects both called "data"), the converter typically appends the parent name to disambiguate, producing types like UserData and OrderData.

Unmarshaling Nested Data

var response AutoGenerated
json.Unmarshal([]byte(jsonData), &response)
fmt.Println(response.User.Address.City) // "Springfield"

Go's encoding/json package recursively processes each nested object, matching JSON keys to struct tags at every level. This makes deeply nested structures fully navigable with standard dot notation.

Use Case

APIs for services like Stripe, GitHub, or Twilio frequently return deeply nested JSON responses. Converting them to nested Go structs lets you traverse the response safely with compile-time type checking.

Try It — JSON to Go Struct Converter

Open full tool