Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 147 ยท Standard Library

JSON

Learn encoding/json in Go - Marshal and Unmarshal, struct tags, omitempty and omitzero, decoding into maps and any, Decoder and Encoder, RawMessage, custom marshalers and the new json/v2.

JSON is the lingua franca of web APIs, config files and logs, and Go ships with a complete implementation in the standard library: encoding/json. It converts Go values to JSON text (marshaling) and JSON text back into Go values (unmarshaling), using the fields of your structs and their struct tags as the mapping.

You'll use this package in almost every Go service, so it pays to know its rules well: which fields are visible, what happens to missing and extra keys, how numbers and nil slices are treated, and how to take control with custom methods. At the end of the lesson you'll also meet the new encoding/json/v2 package.

Marshaling: Go to JSON

json.Marshal takes any value and returns []byte plus an error. Struct fields become object members, but only exported fields (capitalized names) take part, because the json package lives outside your package and can't see unexported fields.

Go Marshal a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The tag json:"email,omitempty" renames the key and drops it when the value is "empty": false, 0, a nil pointer or interface, and any empty array, slice, map or string. The tag json:"-" hides a field entirely. Without a tag the key is the Go field name (ID, Name), which is rarely what API consumers expect, so tag every field of a type that crosses a service boundary.

MarshalIndent produces human-readable output: the second argument is a prefix for each line and the third is the indentation.

Things that surprise people

  • A nil slice encodes as null, but an empty non-nil slice encodes as []. The same goes for maps.
  • Map keys are sorted alphabetically in the output, so map encoding is deterministic.
  • Channels, functions and complex numbers can't be encoded. Marshal returns an *json.UnsupportedTypeError.
  • float64 values print in the shortest form that round-trips; NaN and infinity are errors.
  • Strings are escaped for safe embedding in HTML: <, > and & become <, > and &. An Encoder can turn this off (shown below).
Go nil versus empty, omitempty and omitzero

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

omitzero arrived in Go 1.24. It omits a field whose value is the zero value of its type (or reports IsZero() == true if the type has that method), which is the correct tool for structs like time.Time, where omitempty has no effect.

Unmarshaling: JSON to Go

json.Unmarshal takes the JSON bytes and a pointer to the destination. It matches object keys to struct fields, ignoring case, and fills in what it finds:

Go Unmarshal into a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice the three behaviors on display:

  • "PRICE" still filled Price: v1 matching is case-insensitive.
  • "colour" has no matching field, so it was silently ignored.
  • stock was missing, so it keeps its previous value (here the zero value 0).

Because a missing key and a zero value look the same afterwards, use a pointer field (*int) when you must tell "absent" from "zero".

When decoding fails

Syntax errors and type mismatches are reported as errors you can inspect with errors.As:

Go Syntax and type errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A type mismatch doesn't stop the decoder: it keeps going, fills what it can and reports the first mismatch at the end. Passing a non-pointer yields an *json.InvalidUnmarshalError.

Unknown shapes: maps and any

When you don't know the structure ahead of time, decode into map[string]any or just any. JSON objects become map[string]any, arrays become []any, strings stay string, booleans bool, null becomes nil, and every number becomes float64.

Go Decoding into any

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Dynamic decoding is handy for exploring data but easy to get wrong: you pay for type assertions at every step (type assertions), and large integers lose precision as float64. Prefer a struct whenever you know the shape. If you must keep integers exact, call decoder.UseNumber(), which turns numbers into json.Number strings you can convert with Int64() or Float64().

Streaming with Decoder and Encoder

Marshal and Unmarshal work on whole byte slices. For files, network connections and HTTP bodies, json.NewDecoder(r) and json.NewEncoder(w) read from and write to an io.Reader or io.Writer directly, and they can process a stream of values one after another (a format often called JSON Lines):

Go Decoder and Encoder streams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Decode returns io.EOF when the stream ends cleanly. DisallowUnknownFields makes extra keys an error, which is a good idea for config files where a typo should not pass silently. Always use a Decoder on HTTP request bodies, and wrap the body in http.MaxBytesReader so a client can't make your server read gigabytes.

Unmarshal requires the whole input to be one valid JSON value; trailing garbage is an error. Decoder.Decode stops after the first value and leaves the rest in the stream. If you only expect one value, check afterwards that dec.More() is false or that another Decode returns io.EOF.

Delaying work with RawMessage

json.RawMessage is a []byte that keeps a piece of JSON undecoded. It's the standard way to handle envelopes whose payload type depends on another field:

Go RawMessage envelope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Custom encoding: Marshaler interfaces

A type takes over its own JSON form by implementing json.Marshaler (MarshalJSON() ([]byte, error)) and json.Unmarshaler (UnmarshalJSON([]byte) error). A simpler route for types that map to a string is encoding.TextMarshaler and TextUnmarshaler; the json package uses them automatically, including for map keys.

Go A Status enum that encodes as text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Two rules to remember. Implement UnmarshalJSON/UnmarshalText on a pointer receiver, because it must modify the value. And inside MarshalJSON never call json.Marshal on the receiver's own type without a trick (an alias type without the method), or you'll recurse forever.

The new encoding/json/v2

Go's original encoding/json ("v1") has well-known quirks: case-insensitive matching, silent acceptance of duplicate keys, nil slices as null, and slow decoding for large inputs. A redesigned package, encoding/json/v2 (with a companion encoding/json/jsontext for low-level tokens), exists to fix them. In Go 1.25 it was available only behind GOEXPERIMENT=jsonv2; in the toolchain that runs our examples it can be imported directly.

Go encoding/json/v2 behaves differently

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The v2 API takes options (such as json.Deterministic(true)) as trailing arguments and is stricter by default. For new code that you control, v2 is worth trying once it's stable in your toolchain; for libraries and existing services, encoding/json remains what everyone uses, and everything in the rest of this lesson applies to it. The two packages share struct tags, so switching later is mostly a matter of testing the behavior differences.

Marshaling is reflection-based, so it is not the fastest option. Measure before reaching for third-party libraries; for most services JSON speed is not the bottleneck. The struct-tag details (including string, inline and custom tags) are covered in Struct Tags.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a struct field name string (lowercase) missing from the output of json.Marshal?

    The json package is outside your package, so it can only use exported (capitalized) fields.
  2. 2. What does json.Marshal produce for a nil []int field tagged json:"xs"?

    A nil slice becomes null. An empty but non-nil slice becomes []. Only omitempty or omitzero would drop the key.
  3. 3. Into what Go type does json.Unmarshal decode the number 42 when the destination is any?

    Every JSON number becomes float64 unless you call UseNumber on a Decoder.
  4. 4. Why must you pass &p rather than p to Unmarshal?

    Go passes arguments by value. Without a pointer, Unmarshal could only change a copy, so it returns an error instead.
  5. 5. Which tool lets you read a field called type first and decode the payload field later, depending on it?

    RawMessage keeps the unparsed bytes of a value so you can decode them into the right type once you know it.

Summary

  • json.Marshal and json.Unmarshal convert between Go values and JSON; only exported fields take part.
  • Struct tags rename keys (json:"name"), omitempty drops empty values, omitzero (Go 1.24) drops zero values such as time.Time{}, and json:"-" hides a field.
  • A nil slice or map encodes as null; map keys come out sorted.
  • Unmarshal needs a pointer, matches keys case-insensitively, ignores unknown keys and keeps values for missing ones.
  • Decoding into any yields map[string]any, []any and float64 numbers.
  • Decoder and Encoder stream values from and to readers and writers; DisallowUnknownFields catches typos.
  • json.RawMessage delays decoding; MarshalJSON/UnmarshalJSON and the text variants customize a type's encoding.
  • encoding/json/v2 is a stricter redesign with options such as json.Deterministic.

Next: CSV, XML and Other Encodings covers the other formats in the standard library.