0Pricing
Go Academy · Lesson

JSON Encoding and Decoding

Marshal, Unmarshal, and struct tags

JSON Encoding and Decoding is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

encoding/json overview

Go's encoding/json package marshals Go values to JSON and unmarshals JSON back to Go values using struct tags and reflection.

json.Marshal

json.Marshal converts a Go value to JSON bytes. Returns an error for unsupported types (channels, functions, complex numbers).

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
u := User{Name: "Alice", Age: 30}
data, err := json.Marshal(u)
fmt.Println(string(data)) // {"name":"Alice","age":30}

json.Unmarshal

json.Unmarshal decodes JSON into a Go value. The target must be a pointer.

var u User
err := json.Unmarshal(data, &u)
fmt.Println(u.Name) // "Alice"

Struct tags

Use json: struct tags to control field names, omit empty values, and skip unexported fields.

type Product struct {
    ID    int    `json:"id"`
    Price float64 `json:"price,omitempty"` // omit if zero
    secret string // unexported: ignored
}

json.Encoder / json.Decoder

For streaming (HTTP response/request bodies), use Encoder and Decoder instead of Marshal/Unmarshal to avoid loading the entire payload into memory.

// Writing
json.NewEncoder(w).Encode(user)
// Reading
var u User
json.NewDecoder(r.Body).Decode(&u)

Decoding into map[string]any

Decode unknown JSON into a generic map:

var m map[string]any
json.Unmarshal(data, &m)
fmt.Println(m["name"])

json.Number

By default, numbers in generic maps decode as float64. Use decoder.UseNumber() to decode them as json.Number preserving precision.

dec := json.NewDecoder(r)
dec.UseNumber()
var m map[string]any
dec.Decode(&m)

Custom marshaling

Implement json.Marshaler or json.Unmarshaler to control encoding/decoding for a type, e.g., for custom date formats.

func (d Date) MarshalJSON() ([]byte, error) {
    return json.Marshal(d.Format("2006-01-02"))
}

Omitting fields

Use omitempty to skip zero values. Use json:"-" to always exclude a field from JSON output regardless of value.

Hidden string `json:"-"`

Handling null

JSON null unmarshals to a Go zero value for scalars, or sets a pointer to nil. Marshal a nil pointer as null.

Pretty printing

Use json.MarshalIndent for human-readable output:

data, _ := json.MarshalIndent(u, "", "  ")

Quick Check

What does the struct tag `json:"name,omitempty"` do?

Recap: JSON Encoding and Decoding

Key points:

  • json.Marshal/Unmarshal for in-memory; Encoder/Decoder for streams
  • Struct tags control names, omitempty, and exclusion
  • Custom types implement Marshaler/Unmarshaler
  • Use json.MarshalIndent for debug output

Frequently asked questions

Is the “JSON Encoding and Decoding” lesson free?

Yes — the full text of “JSON Encoding and Decoding” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “JSON Encoding and Decoding”?

Marshal, Unmarshal, and struct tags You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “JSON Encoding and Decoding” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading Files with os and bufio
  2. Writing Files and Temp Files
  3. JSON Encoding and Decoding
  4. Streaming JSON and CSV
← Back to Go Academy