Back to Blog

JSON Tutorial - Marshal, Unmarshal, Struct Tags & Nested Data | Go Tutorial #23

Sandy LaneSandy Lane

Video: JSON Tutorial - Marshal, Unmarshal, Struct Tags & Nested Data | Go Tutorial #23 by Taught by Celeste AI - AI Coding Coach

Watch full page →

JSON Tutorial in Go: Marshal, Unmarshal, Struct Tags & Nested Data

Working with JSON in Go is straightforward using the encoding/json package. This tutorial demonstrates how to convert Go structs to JSON and back, customize JSON output with struct tags, and handle nested JSON data structures effectively.

Code

package main

import (
  "encoding/json"
  "fmt"
)

// Define a nested struct for Address
type Address struct {
  Street string `json:"street"`
  City   string `json:"city,omitempty"` // Omit if empty
  Zip    string `json:"zip"`
}

// User struct with JSON tags
type User struct {
  ID      int      `json:"id"`
  Name    string   `json:"name"`
  Email   string   `json:"email,omitempty"`  // Skip if empty
  Address Address  `json:"address"`          // Nested struct
  Secret  string   `json:"-"`                // Exclude from JSON
}

func main() {
  // Create an instance of User
  user := User{
    ID:    1,
    Name:  "Alice",
    Email: "",
    Address: Address{
      Street: "123 Go Lane",
      City:   "",
      Zip:    "12345",
    },
    Secret: "my_password",
  }

  // Marshal to JSON (compact)
  jsonData, err := json.Marshal(user)
  if err != nil {
    panic(err)
  }
  fmt.Println("Compact JSON:", string(jsonData))

  // Marshal to pretty JSON
  prettyJSON, err := json.MarshalIndent(user, "", "  ")
  if err != nil {
    panic(err)
  }
  fmt.Println("Pretty JSON:\n", string(prettyJSON))

  // Example JSON input to unmarshal
  inputJSON := `{
    "id": 2,
    "name": "Bob",
    "email": "bob@example.com",
    "address": {
      "street": "456 Gopher St",
      "city": "Go City",
      "zip": "67890"
    }
  }`

  var user2 User
  err = json.Unmarshal([]byte(inputJSON), &user2)
  if err != nil {
    panic(err)
  }
  fmt.Printf("Unmarshaled struct: %+v\n", user2)
}

Key Points

  • Use json.Marshal to convert Go structs into JSON bytes and json.MarshalIndent for readable formatting.
  • json.Unmarshal parses JSON data back into Go structs, requiring a pointer to the struct.
  • Struct tags like `json:"name"` customize JSON field names; `omitempty` skips zero-value fields.
  • Use `json:"-"` tag to exclude sensitive or unwanted fields from JSON output.
  • Nested JSON objects map naturally to embedded structs within Go structs for hierarchical data.