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
| API | Use it when |
|---|---|
json.Marshal / json.Unmarshal | you 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
| Go | JSON | Notes |
|---|---|---|
bool | boolean | |
| any int, uint, float | number | NaN and Inf are a marshal error |
string | string | invalid UTF-8 is replaced with U+FFFD |
[]byte | base64 string | not an array of numbers |
| slice, array | array | a nil slice is null; an empty one is [] |
| map | object | keys sorted; key type must be a string, an integer, or a TextMarshaler |
| struct | object | exported fields only, in declaration order |
| pointer, interface | the pointee, or null | |
chan, func, complex | marshal error | json: unsupported type |
| a reference cycle | marshal error | json: 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
| Wire | Stock int | Stock *int |
|---|---|---|
{"stock":9} | 9 | points at 9 |
{"stock":0} | 0 | points at 0 |
{"stock":null} | 0 | nil |
{} | 0 | nil |
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
| Type | Tells you |
|---|---|
*json.SyntaxError | Offset: the byte where the document stopped making sense |
*json.UnmarshalTypeError | Value, Type, Struct, Field, Offset: exactly which field did not fit |
*json.InvalidUnmarshalError | you passed a non-pointer or a nil pointer |
*json.UnsupportedTypeError | a 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
- Passing a value instead of a pointer to
Unmarshal.json.Unmarshal(data, o)whereois anOrdercompiles cleanly and fails at run time withjson: Unmarshal(non-pointer main.Order). The decoder needs somewhere to write; a copy is nowhere. The same applies toDecoder.Decode.
- Expecting unexported fields to travel. A lowercase field is invisible to the
encoding/jsonpackage: 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.
- Ignoring the error and reading the struct anyway.
json.Unmarshalreports 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.
- Assuming
Unmarshalresets 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.
- Using
float64for money or for large integers. Every JSON number lands in afloat64when the destination isany, andfloat64cannot represent10000000000000001or exactly represent49.99. Decode money as an integer count of the smallest unit, and usejson.Numberor a concreteint64field when the digits matter.
- Type asserting a decoded number to
int. After decoding intoany,v.(int)panics and the two value formn, ok := v.(int)silently yields0, false, because the dynamic type isfloat64. Assert tofloat64and convert, switch onjson.Number, or -- far better -- decode into a struct.
- Conflating absent,
nulland zero. All three leave anintfield reading0and astringfield 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 apresentflag, or ajson.RawMessageyou inspect yourself.
- Calling
json.Marshalon the receiver insideMarshalJSON. 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.
- Forgetting that
[]bytebecomes base64. A[]bytefield marshals to a base64 string, not a JSON array of numbers, and decodes back the same way.[]uint8is the same type and behaves identically. If you genuinely want an array of numbers, use[]int, or give a defined type over[]byteits ownMarshalJSON.
- Letting unknown fields pass in silence. By default a key with no matching field is discarded without comment, so
"timeuot": 30in a config file does exactly nothing and takes the default with it. CallDecoder.DisallowUnknownFieldson anything a human is expected to hand-write.
- 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 anEncoderwithSetEscapeHTML(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]anyonly when the shape is genuinely unknown at compile time, and even then only for the part that is unknown.
- Stream with
DecoderandEncoder, and bound the input. Decoding straight fromhttp.Response.Bodyor a file avoids buffering the whole document, andEncoder.Encodewrites one value plus a newline, which is exactly the NDJSON format above. On a server, wrap the body inhttp.MaxBytesReaderfirst: an unbounded decode is a memory limit set by whoever is talking to you.
- Use
DisallowUnknownFieldson human input, not on a wire protocol. A config file or a CLI payload should rejecttimeuotloudly. 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.
*intand apresent boolboth 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.RawMessageto 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.SyntaxErrorcarries a byteOffset,*json.UnmarshalTypeErrorcarries theFieldand both types, and*json.InvalidUnmarshalErrormeans the calling code passed the wrong thing. Wrap them with%wso callers can still useerrors.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
- 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 plainstringfield cannot tell apart.
- A Custom Marshaller for Money: Define
type Cents int64withMarshalJSONemitting a plain number of pence andUnmarshalJSONaccepting either4999or"49.99". Give it aStringmethod that prints49.99. Then round trip a struct containing one, and confirm with a test that"0.05"and5both decode to the same value -- something afloat64field cannot promise.
- Break the Stream on Purpose: Take
decodeStreamand 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 useerrors.Asto pull out the*json.SyntaxErrorand report itsOffset. Now change thebreakto acontinueand explain in a comment what the following records decode to and why the numbering goes wrong.
- 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 taggedjson:"extra"of typemap[string]json.RawMessage-- for the plugin settings you deliberately pass through untouched. Explain why the strict top level and the tolerantextraobject are both right, and whyencoding/jsongives you no way to catch stray keys implicitly.