JSON Serialization

JSON Serialization in Go: You cannot post an armchair. What you can post is a flat box of parts with a numbered manifest, and the person at the other end…

The Analogy: Flat-Packing the Armchair

You cannot post an armchair. What you can post is a flat box of parts with a numbered manifest, and the person at the other end rebuilds it. Marshalling is the flat-pack; unmarshalling is the reassembly. Nothing about the armchair travels -- only a description of it, in a form both ends have agreed on.

The agreement is everything. If the manifest says "part 4: left arm" and the recipient's instructions call that part 7, the chair comes out wrong, and nothing in the box will tell them. Struct tags are the part numbers, which is why the previous lesson spent its time on them: they are how the sender and the receiver agree on names without either one having to know the other's internal vocabulary.

The catalogue is also much smaller than reality. JSON knows exactly six kinds of thing: object, array, string, number, boolean, and null. It has no concept of a 64-bit integer as distinct from a float, no timestamp type, no byte array, no distinction between a signed and an unsigned quantity. Go has hundreds of types. So every value that travels is projected onto those six, and every projection loses something -- encoding/json simply picks sensible defaults for the loss and gives you hooks to override them.

You notice the loss the first time you decode into an any. Every number comes back as a float64, every object as a map[string]any, and an order id of 10000000000000001 comes back as 1e+16. That is not a bug; that is the catalogue being smaller than reality, and the whole lesson is about choosing the projection deliberately rather than discovering it in production.


Syntax or Core Structure

package main

import (
	"encoding/json"
	"fmt"
	"time"
)

type Order struct {
	ID      int            `json:"id"`
	Total   float64        `json:"total"`
	Paid    bool           `json:"paid"`
	Tags    []string       `json:"tags"`
	Meta    map[string]int `json:"meta"`
	Note    *string        `json:"note"`
	Blob    []byte         `json:"blob"`
	Placed  time.Time      `json:"placed"`
	Missing []int          `json:"missing"`
}

func main() {
	o := Order{
		ID:     7,
		Total:  19.5,
		Paid:   true,
		Tags:   []string{"rush", "gift"},
		Meta:   map[string]int{"zeta": 1, "alpha": 2, "mid": 3},
		Blob:   []byte("hi"),
		Placed: time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC),
	}

	b, err := json.Marshal(o)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))

	pretty, _ := json.MarshalIndent(o.Meta, "", "  ")
	fmt.Println(string(pretty))

	// Decoding into any: what the six JSON types actually become.
	var loose any
	_ = json.Unmarshal([]byte(`{"n":1,"big":10000000000000001,"s":"x","t":true,"z":null,"a":[1,"two"]}`), &loose)
	m := loose.(map[string]any)
	for _, k := range []string{"n", "big", "s", "t", "z", "a"} {
		fmt.Printf("%-4s %-12T %v\n", k, m[k], m[k])
	}
}

Output:

{"id":7,"total":19.5,"paid":true,"tags":["rush","gift"],"meta":{"alpha":2,"mid":3,"zeta":1},"note":null,"blob":"aGk=","placed":"2026-03-04T05:06:07Z","missing":null}
{
  "alpha": 2,
  "mid": 3,
  "zeta": 1
}
n    float64      1
big  float64      1e+16
s    string       x
t    bool         true
z    <nil>        <nil>
a    []interface {} [1 two]

Five defaults are visible in the first line alone. Map keys came out sorted -- alpha, mid, zeta, not the order they were written -- which is what makes marshalled output reproducible. The []byte became the base64 string "aGk=" rather than an array of numbers. The nil *string and the nil []int both became null, indistinguishable from each other on the wire. And time.Time became an RFC 3339 string because it implements MarshalJSON itself, not because encoding/json knows anything about time.

The last six lines are the projection running backwards, and big is the one to remember: 10000000000000001 arrived as a float64, which cannot represent that value, so it silently became 1e+16. Decoding an id or a monetary amount into an any loses data, quietly, in a way no error tells you about.


Technical Depth: Controlling the Projection

Two APIs, different jobs

APIUse it when
json.Marshal / json.Unmarshalyou have, or want, the whole document as []byte
json.NewEncoder(w).Encode(v)writing to a stream; appends a trailing newline, which is exactly NDJSON
json.NewDecoder(r).Decode(&v)reading a stream; one value per call, More() reports whether another follows

The decoder is the only way to read several JSON values from one reader, and the only way to process a large document without holding it all in memory. It also carries the options: DisallowUnknownFields, UseNumber, and Token for a streaming parse.

The default projection, in both directions

GoJSONNotes
boolboolean
any int, uint, floatnumberNaN and Inf are a marshal error
stringstringinvalid UTF-8 is replaced with U+FFFD
[]bytebase64 stringnot an array of numbers
slice, arrayarraya nil slice is null; an empty one is []
mapobjectkeys sorted; key type must be a string, an integer, or a TextMarshaler
structobjectexported fields only, in declaration order
pointer, interfacethe pointee, or null
chan, func, complexmarshal errorjson: unsupported type
a reference cyclemarshal errorjson: unsupported value: encountered a cycle

Decoding into an any uses a fixed reverse mapping: object to map[string]any, array to []any, string to string, number to float64, boolean to bool, null to nil.

json.Number for numbers you cannot afford to round

dec := json.NewDecoder(r)
dec.UseNumber() // numbers arrive as json.Number, a string with Int64/Float64
var v any
_ = dec.Decode(&v)
n := v.(map[string]any)["big"].(json.Number)
id, err := n.Int64() // exact, or an error if it does not fit

Use this whenever a document holds 64-bit ids or amounts and you cannot change the struct to a typed one. In your own types, model money as an integer count of minor units (Pence int64), never as a float64.

Absent, null, and zero are three different things

WireStock intStock *int
{"stock":9}9points at 9
{"stock":0}0points at 0
{"stock":null}0nil
{}0nil

A pointer separates "explicitly zero" from "not sent", which is what a PATCH endpoint needs. To tell null apart from absent as well, decode into map[string]json.RawMessage and check for the key.

Unmarshal merges into what is already there

v := []int{1, 2, 3}
json.Unmarshal([]byte(`[9]`), &v) // v is []int{9}: the length is reset

m := map[string]int{"a": 1}
json.Unmarshal([]byte(`{"b":2}`), &m) // m is {"a":1,"b":2}: "a" survives

s := Order{ID: 5, Paid: true}
json.Unmarshal([]byte(`{"id":9}`), &s) // s.Paid is STILL true

Slices are truncated and refilled, but maps keep their existing entries and struct fields absent from the document are left completely untouched. Decode into a fresh zero value whenever you want the document to be the only source of truth.

Custom marshalling, and the recursion trap

type Celsius float64

func (c Celsius) MarshalJSON() ([]byte, error) {
	return json.Marshal(fmt.Sprintf("%.1fC", float64(c)))
}

// WRONG: json.Marshal(o) calls this method again, forever.
func (o Order) MarshalJSON() ([]byte, error) { return json.Marshal(o) }

// RIGHT: a local type has the same layout but none of the methods.
func (o Order) MarshalJSON() ([]byte, error) {
	type plain Order
	return json.Marshal(struct {
		plain
		Kind string `json:"kind"`
	}{plain(o), "order"})
}

UnmarshalJSON must be declared on a pointer receiver, since it has to modify the value. If no MarshalJSON exists, encoding/json falls back to encoding.TextMarshaler, which is also what lets a non-string type be used as a map key.

json.RawMessage defers a decision

type envelope struct {
	Kind string          `json:"kind"`
	Data json.RawMessage `json:"data"`
}

RawMessage is a []byte that marshals verbatim and unmarshals by copying the raw bytes, so you can read the discriminator first and decode the payload once you know its type. This is Go's standard answer to polymorphic JSON, and it is the subject of the next section.

Errors worth type-asserting

TypeTells you
*json.SyntaxErrorOffset: the byte where the document stopped making sense
*json.UnmarshalTypeErrorValue, Type, Struct, Field, Offset: exactly which field did not fit
*json.InvalidUnmarshalErroryou passed a non-pointer or a nil pointer
*json.UnsupportedTypeErrora chan, func or complex was in the value

Unmarshal stops at the first error, but fields decoded before it are already written -- so a failed decode leaves a partially populated value that must be discarded rather than inspected.

Two encoder options people trip over

enc.SetIndent("", " ") produces the same layout as MarshalIndent. enc.SetEscapeHTML(false) turns off the default escaping of <, > and & into \u003c and friends -- that escaping is safe for embedding JSON in HTML and confusing everywhere else.


Real World Example: A Polymorphic Event Stream

An event log arrives as newline-delimited JSON, every record shaped {"kind":..., "data":...}, and each kind has a different payload. Go has no inheritance to lean on, so the answer is a discriminator, a RawMessage, and a registry.

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"strings"
	"time"
)

type Event interface {
	Kind() string
	Summary() string
}

type Created struct {
	SKU   string `json:"sku"`
	Name  string `json:"name"`
	Stock int    `json:"stock"`
}

func (Created) Kind() string { return "created" }
func (c Created) Summary() string {
	return fmt.Sprintf("created %s (%s) stock=%d", c.SKU, c.Name, c.Stock)
}

type Shipped struct {
	SKU   string    `json:"sku"`
	Count int       `json:"count"`
	When  time.Time `json:"when"`
}

func (Shipped) Kind() string { return "shipped" }
func (s Shipped) Summary() string {
	return fmt.Sprintf("shipped %d of %s on %s", s.Count, s.SKU, s.When.Format("2006-01-02"))
}

type Priced struct {
	SKU   string `json:"sku"`
	Pence int64  `json:"pence"`
}

func (Priced) Kind() string { return "priced" }
func (p Priced) Summary() string {
	return fmt.Sprintf("priced %s at %d.%02d", p.SKU, p.Pence/100, p.Pence%100)
}

type envelope struct {
	Kind string          `json:"kind"`
	Data json.RawMessage `json:"data"`
}

// registry maps a discriminator to a constructor. Each entry returns a pointer,
// because UnmarshalJSON and Decode both need something addressable.
var registry = map[string]func() Event{
	"created": func() Event { return &Created{} },
	"shipped": func() Event { return &Shipped{} },
	"priced":  func() Event { return &Priced{} },
}
// decodeStream reads newline delimited envelopes and turns each one into an
// Event. A record that is merely wrong is reported and skipped. A record that
// breaks the syntax stops the loop, because after a syntax error the decoder's
// position in the stream is no longer known.
func decodeStream(r io.Reader) ([]Event, []error) {
	dec := json.NewDecoder(r)
	var (
		events   []Event
		problems []error
	)
	for n := 1; dec.More(); n++ {
		var env envelope
		if err := dec.Decode(&env); err != nil {
			problems = append(problems, fmt.Errorf("record %d: %w", n, err))
			break
		}
		newEvent, ok := registry[env.Kind]
		if !ok {
			problems = append(problems, fmt.Errorf("record %d: unknown kind %q", n, env.Kind))
			continue
		}
		ev := newEvent()
		if err := json.Unmarshal(env.Data, ev); err != nil {
			problems = append(problems, fmt.Errorf("record %d (%s): %w", n, env.Kind, err))
			continue
		}
		events = append(events, ev)
	}
	return events, problems
}
func main() {
	const stream = `
{"kind":"created","data":{"sku":"kb-01","name":"Keyboard","stock":4}}
{"kind":"shipped","data":{"sku":"kb-01","count":2,"when":"2026-03-04T05:06:07Z"}}
{"kind":"priced","data":{"sku":"kb-01","pence":4999}}
{"kind":"scrapped","data":{"sku":"kb-01"}}
{"kind":"shipped","data":{"sku":"kb-01","count":"two"}}
{"kind":"created","data":{"sku":"ms-02","name":"Mouse","stock":11}}
`

	events, problems := decodeStream(strings.NewReader(stream))

	fmt.Println("--- events ---")
	for _, ev := range events {
		fmt.Println(" ", ev.Summary())
	}

	fmt.Println("--- problems ---")
	for _, err := range problems {
		fmt.Println(" ", err)
		var te *json.UnmarshalTypeError
		if errors.As(err, &te) {
			fmt.Printf("    field=%s wanted=%s got=%s\n", te.Field, te.Type, te.Value)
		}
	}

	fmt.Println("--- re-encoded ---")
	enc := json.NewEncoder(os.Stdout)
	for _, ev := range events {
		payload, err := json.Marshal(ev)
		if err != nil {
			fmt.Println(" ", err)
			continue
		}
		if err := enc.Encode(envelope{Kind: ev.Kind(), Data: payload}); err != nil {
			fmt.Println(" ", err)
		}
	}
}

Output:

--- events ---
  created kb-01 (Keyboard) stock=4
  shipped 2 of kb-01 on 2026-03-04
  priced kb-01 at 49.99
  created ms-02 (Mouse) stock=11
--- problems ---
  record 4: unknown kind "scrapped"
  record 5 (shipped): json: cannot unmarshal string into Go struct field Shipped.count of type int
    field=count wanted=int got=string
--- re-encoded ---
{"kind":"created","data":{"sku":"kb-01","name":"Keyboard","stock":4}}
{"kind":"shipped","data":{"sku":"kb-01","count":2,"when":"2026-03-04T05:06:07Z"}}
{"kind":"priced","data":{"sku":"kb-01","pence":4999}}
{"kind":"created","data":{"sku":"ms-02","name":"Mouse","stock":11}}

The envelope is the whole trick. JSON has no type tags, so a stream of mixed records has to carry its own discriminator, and the decoder cannot know which Go type to build until it has read that discriminator. json.RawMessage breaks the decode into two passes over the same bytes: the first pass reads kind and parks data as an unexamined byte slice, and the second pass decodes those bytes into the concrete type the discriminator named. Without RawMessage you would decode into map[string]any and then copy fields out by hand, losing every type check the standard library was willing to do for you.

The registry is a map from discriminator to constructor, and it is worth preferring over a switch for two reasons: a new event kind is one map entry rather than a new case in a function that keeps growing, and the set of known kinds becomes a value you can range over, count, or print in an error message. Each constructor returns a pointer, because Unmarshal needs somewhere to write. The two exits from the loop are also deliberate. An unknown kind or a bad payload is a bad record, so the loop records the problem and reads the next one; a syntax error means the decoder no longer knows where the next record starts, so the loop stops. Getting that distinction backwards gives you either a parser that abandons a million good records because of one typo, or one that spins through garbage reporting nonsense.

Typed errors are what turn "invalid JSON" into something a support engineer can act on. The raw message already names the offending field, but errors.As gets you the struct behind it, so you can report field=count wanted=int got=string in your own format, attach the record number, or decide that a type error on an optional field is only a warning. Note the trap that comes with it: when Unmarshal fails partway through, it does not roll back. The Shipped value from record 5 had its sku populated before count failed, which is exactly why the code discards it rather than appending it to events. A partially decoded value is not a value you should keep.

Two smaller decisions carry their weight quietly. Decoder and Encoder stream, so this program would behave the same on a six line file and a six gigabyte one -- nothing here ever holds more than one record's bytes, and dec.More() is the whole loop condition. And money is an int64 count of pence, formatted for display only in Summary. Decode 49.99 into a float64 and you have accepted a value that cannot be represented exactly, so sums drift; keep it an integer and the arithmetic is exact, the JSON is exact, and the decimal point exists only in the last line of output.


Common Mistakes

  1. Passing a value instead of a pointer to Unmarshal. json.Unmarshal(data, o) where o is an Order compiles cleanly and fails at run time with json: Unmarshal(non-pointer main.Order). The decoder needs somewhere to write; a copy is nowhere. The same applies to Decoder.Decode.
  1. Expecting unexported fields to travel. A lowercase field is invisible to the encoding/json package: it is omitted on the way out and never populated on the way in, with no error either way. If a value must survive a round trip it needs an exported field, and if you want the JSON name to stay lowercase, that is what the tag is for.
  1. Ignoring the error and reading the struct anyway. json.Unmarshal reports the first problem it hits, and everything before that problem has already been written. A struct whose decode failed is a mixture of decoded fields and zero values, which is worse than either -- it looks populated. Check the error and discard the value.
  1. Assuming Unmarshal resets the destination. Decoding merges into whatever is already there: fields absent from the JSON keep their previous contents, and existing map entries and slice elements beyond the incoming length survive. Reusing one struct across a loop of records quietly carries data forward. Declare it inside the loop.
  1. Using float64 for money or for large integers. Every JSON number lands in a float64 when the destination is any, and float64 cannot represent 10000000000000001 or exactly represent 49.99. Decode money as an integer count of the smallest unit, and use json.Number or a concrete int64 field when the digits matter.
  1. Type asserting a decoded number to int. After decoding into any, v.(int) panics and the two value form n, ok := v.(int) silently yields 0, false, because the dynamic type is float64. Assert to float64 and convert, switch on json.Number, or -- far better -- decode into a struct.
  1. Conflating absent, null and zero. All three leave an int field reading 0 and a string field reading "". If the difference matters -- a PATCH request, a field with a non-zero default -- the field has to be a pointer, a wrapper with a present flag, or a json.RawMessage you inspect yourself.
  1. Calling json.Marshal on the receiver inside MarshalJSON. The method calls the package, the package calls the method, and the goroutine dies of stack exhaustion. Convert to a defined type with the same fields and no methods first (type plain Order Order), then marshal that.
  1. Forgetting that []byte becomes base64. A []byte field marshals to a base64 string, not a JSON array of numbers, and decodes back the same way. []uint8 is the same type and behaves identically. If you genuinely want an array of numbers, use []int, or give a defined type over []byte its own MarshalJSON.
  1. Letting unknown fields pass in silence. By default a key with no matching field is discarded without comment, so "timeuot": 30 in a config file does exactly nothing and takes the default with it. Call Decoder.DisallowUnknownFields on anything a human is expected to hand-write.
  1. Being surprised by \u003c. The standard marshaller escapes <, > and & so that output is safe to embed in HTML, so a URL with a query string comes back looking mangled. It is still valid JSON and any decoder restores the original characters; if you need the literal bytes, use an Encoder with SetEscapeHTML(false).

Best Practices

  • Give every payload you own a struct. A struct documents the shape, gets you compile time field names, and lets the decoder reject a string where a number belongs. Reach for map[string]any only when the shape is genuinely unknown at compile time, and even then only for the part that is unknown.
  • Stream with Decoder and Encoder, and bound the input. Decoding straight from http.Response.Body or a file avoids buffering the whole document, and Encoder.Encode writes one value plus a newline, which is exactly the NDJSON format above. On a server, wrap the body in http.MaxBytesReader first: an unbounded decode is a memory limit set by whoever is talking to you.
  • Use DisallowUnknownFields on human input, not on a wire protocol. A config file or a CLI payload should reject timeuot loudly. A message from another service should tolerate fields you have not heard of, because that tolerance is what lets the producer add one without a coordinated deploy.
  • Keep the wire type separate from the domain type once they diverge. When the JSON needs a shape your internal struct should not have, declare a second struct for the wire, put the tags there, and convert between them. It costs one conversion function and buys the freedom to refactor either side alone.
  • Reach for a pointer or a wrapper only when absent must differ from zero. *int and a present bool both cost you nil checks at every use, so pay that price where it earns something -- partial updates, defaults that are not the zero value -- and use plain fields everywhere else.
  • Use json.RawMessage to defer a decision, not to avoid one. It is the right tool for a discriminated payload, for a blob you must forward untouched, and for a field whose type depends on another field. It is the wrong tool for "I could not work out the type", because the decision only moves further from the schema.
  • Branch on the typed errors when the message reaches a human. *json.SyntaxError carries a byte Offset, *json.UnmarshalTypeError carries the Field and both types, and *json.InvalidUnmarshalError means the calling code passed the wrong thing. Wrap them with %w so callers can still use errors.As.
  • Round trip your types in a test. Marshal a fully populated value, unmarshal it into a fresh one, and compare with reflect.DeepEqual; then keep a golden file of the exact expected JSON. The first test catches a tag you forgot, and the second catches the day someone renames a field and breaks every consumer.

Practice Exercises

  1. Absent, Null and Zero: Define type Patch struct { Name *string; Stock *int; Tags []string } with tags, then decode four documents into it: {}, {"name":null}, {"name":""} and {"name":"kb","stock":0}. Print for each field whether it was absent, explicitly null, or present with a value, and write down which of the three cases a plain string field cannot tell apart.
  1. A Custom Marshaller for Money: Define type Cents int64 with MarshalJSON emitting a plain number of pence and UnmarshalJSON accepting either 4999 or "49.99". Give it a String method that prints 49.99. Then round trip a struct containing one, and confirm with a test that "0.05" and 5 both decode to the same value -- something a float64 field cannot promise.
  1. Break the Stream on Purpose: Take decodeStream and feed it a document where record 3 is {"kind":"created","data":{ -- truncated mid object. Print how many events and how many problems come back, then use errors.As to pull out the *json.SyntaxError and report its Offset. Now change the break to a continue and explain in a comment what the following records decode to and why the numbering goes wrong.
  1. A Forward Compatible Config: Write a loader that decodes a config file into a struct with DisallowUnknownFields, and have it report the offending key when a field is misspelled. Then add an explicit escape hatch -- a field tagged json:"extra" of type map[string]json.RawMessage -- for the plugin settings you deliberately pass through untouched. Explain why the strict top level and the tolerant extra object are both right, and why encoding/json gives you no way to catch stray keys implicitly.