Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers

Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.

~5 min readGo
#Go#JSON#Serialization
3D illustration of a Go struct converting bidirectionally into JSON streams through tagged field conduits

encoding/json converts between Go values and JSON text through reflection over exported struct fields. The two entry points are json.Marshal and json.Unmarshal, the mapping is controlled by struct tags, and the friction comes from the places where Go's type system and JSON's data model disagree: no struct tags for a field name that is not an identifier, no distinction between a missing field and a zero value, null for a nil slice, and numbers that arrive as float64 unless told otherwise.

Quick Summary

  • Only exported fields are marshaled; unexported fields are invisible to the encoder.
  • The tag json:"name" renames a field, json:"-" skips it, and ,omitempty omits zero values.
  • omitempty does not omit a zero struct, a zero time.Time, or a zero-length array — use a pointer or omitzero (Go 1.24+) for those.
  • ,string encodes a number or boolean as a JSON string; on a string field it double-encodes.
  • Embedded structs are flattened into the parent object; an embedded field with a tag becomes a nested object.
  • Unmarshal ignores unknown fields by default; Decoder.DisallowUnknownFields turns a typo into an error.
  • Numbers decode into uint64/int64 fields exactly, but into interface{} as float64, where large integers lose precision.
  • A nil slice or map marshals to null; an empty one marshals to [] or {}, and the difference matters to most clients.

Basic syntax and type signatures

go
type Address struct { Street string `json:"street"` City string `json:"city,omitempty"` } type User struct { ID int64 `json:"id"` Name string `json:"name"` Email string `json:"email,omitempty"` Password string `json:"-"` Age int `json:"age,string"` // "42" in JSON CreatedAt time.Time `json:"created_at"` Address *Address `json:"address,omitempty"` Tags []string `json:"tags"` }
go
b, err := json.Marshal(user) if err != nil { return err } var u User if err := json.Unmarshal(b, &u); err != nil { return err } // Streaming, with a decoder for an io.Reader. dec := json.NewDecoder(resp.Body) dec.DisallowUnknownFields() if err := dec.Decode(&u); err != nil { return err } // Pretty output without HTML escaping. enc := json.NewEncoder(os.Stdout) enc.SetEscapeHTML(false) enc.SetIndent("", " ") _ = enc.Encode(u)

The tag grammar is small: a name, then options separated by commas.

TagEffect
json:"-"field is ignored entirely
json:"name"key becomes name
json:",omitempty"omit when the value is zero for its type
json:"name,omitempty"both
json:",string"encode as a JSON string containing the value
json:"-" on an embedded fieldembedding is disabled unless a name is given

Comparison of JSON boundaries

SourceDecode targetPrecisionUnknown fieldsNotes
Struct field int64exactexactignoredbest for ids
Struct field float64exact as floatexact until 2^53ignoredmoney problems
interface{}float64 everywhereloses digits past 2^53keptuse json.Number
json.Numberstring-backedexactn/adecode then parse
map[string]anynested map/[]anysame as interface{}keptflexible, untyped
json.RawMessagedeferred bytesexactdeferredpolymorphic payloads

The first three rows are the choice that matters for ids and money: a 19-digit id decoded into interface{} becomes a float64 and silently changes value, while the same id decoded into an int64 field or a json.Number is preserved.

Practical edge cases and deep dives

1. omitempty, zero structs, and the field clients expect

go
type Config struct { Retries int `json:"retries,omitempty"` // omitted when 0 Timeout time.Duration `json:"timeout,omitempty"` // omitted when 0 Enabled bool `json:"enabled,omitempty"` // omitted when false Meta Meta `json:"meta,omitempty"` // never omitted: struct zero is not "empty" List [3]int `json:"list,omitempty"` // never omitted: arrays have no empty state } b, _ := json.Marshal(Config{}) // {"meta":{"a":0},"list":[0,0,0]}

omitempty checks the zero value of the type: 0, "", false, nil pointers, nil interfaces, and zero-length slices, maps, and strings are omitted. A struct is never zero-length, so Meta always appears; an explicit false is indistinguishable from "unset", which is the classic reason a boolean config field should be a pointer (*bool) when the difference matters. Go 1.24 added omitzero, which omits a struct when it equals its zero value — the fix for the struct row, subject to the module's language version.

The other side is null versus []:

go
var nilSlice []string emptySlice := []string{} a, _ := json.Marshal(nilSlice) // null b, _ := json.Marshal(emptySlice) // []

Most clients treat null as a missing value and fail to iterate it. Initializing the slice at the handler boundary (if s == nil { s = []string{} }) or declaring it with a literal is cheaper than a frontend fix.

2. Custom marshaling without infinite recursion

go
type Money struct { Cents int64 Currency string } func (m Money) MarshalJSON() ([]byte, error) { type moneyJSON struct { // a distinct type, no methods Amount string `json:"amount"` Currency string `json:"currency"` } return json.Marshal(moneyJSON{ Amount: fmt.Sprintf("%.2f", float64(m.Cents)/100), Currency: m.Currency, }) } func (m *Money) UnmarshalJSON(data []byte) error { var raw struct { Amount string `json:"amount"` Currency string `json:"currency"` } if err := json.Unmarshal(data, &raw); err != nil { return err } cents, err := parseAmountToCents(raw.Amount) if err != nil { return fmt.Errorf("money: %w", err) } m.Cents, m.Currency = cents, raw.Currency return nil }

The local moneyJSON type is not a decoration: calling json.Marshal(m) inside MarshalJSON would call the method again and recurse until the stack overflows. A named type with the same fields and no methods breaks the loop. UnmarshalJSON must have a pointer receiver to mutate the value, and returning an error from it aborts the whole decode with that error wrapped in *json.UnmarshalTypeError context — or returned as-is when it is the top-level value.

3. Polymorphic payloads with json.RawMessage

go
type Event struct { Type string `json:"type"` Payload json.RawMessage `json:"payload"` } func handle(data []byte) error { var e Event if err := json.Unmarshal(data, &e); err != nil { return err } switch e.Type { case "user.created": var p struct { ID int64 `json:"id"` Email string `json:"email"` } if err := json.Unmarshal(e.Payload, &p); err != nil { return fmt.Errorf("payload: %w", err) } return onUserCreated(p.ID, p.Email) default: return nil // forward compatibility: ignore unknown types } }

json.RawMessage is []byte with marshal and unmarshal methods, so the payload is deferred until the discriminant is known — the JSON equivalent of a tagged union. The same field marshals back verbatim, which makes this a clean way to proxy a payload between services without a schema. Decoding the whole event twice costs one extra parse and is usually cheaper than a giant struct with every field optional.

4. Numbers, precision, and the float64 default

go
type Order struct { ID int64 `json:"id"` Amount int64 `json:"amount_cents"` } // Wrong: large ids lose precision when decoded into interface{}. var generic map[string]any _ = json.Unmarshal([]byte(`{"id":9007199254740993}`), &generic) fmt.Println(generic["id"]) // 9.007199254740992e+15 // Right: decode into the typed struct. var o Order _ = json.Unmarshal([]byte(`{"id":9007199254740993}`), &o) fmt.Println(o.ID) // 9007199254740993 // Or keep the number as text until it is needed. dec := json.NewDecoder(strings.NewReader(`{"id":9007199254740993}`)) dec.UseNumber() var m map[string]any _ = dec.Decode(&m) n := m["id"].(json.Number) id, _ := n.Int64() fmt.Println(id) // 9007199254740993

The default for a JSON number with no target type is float64, which represents integers exactly only up to 2^53. Anything using map[string]any or any to shuttle JSON — a webhook dispatcher, a proxy, a generic API client — will corrupt 64-bit ids from databases and snowflake generators. UseNumber or typed destination types are the two fixes; json.Number keeps the original text and parses on demand.

5. Errors that identify the field

go
var u User err := json.Unmarshal([]byte(`{"id":"abc","age":42}`), &u) if err != nil { var typeErr *json.UnmarshalTypeError var syntaxErr *json.SyntaxError switch { case errors.As(err, &typeErr): fmt.Printf("field %s: want %s, got %s (offset %d)\n", typeErr.Field, typeErr.Type, typeErr.Value, typeErr.Offset) case errors.As(err, &syntaxErr): fmt.Printf("invalid JSON at byte %d: %v\n", syntaxErr.Offset, err) default: fmt.Println("decode failed:", err) } } // field id: want int64, got number (offset ...)

UnmarshalTypeError.Field is the JSON path of the offending field, which is what makes a 400 response useful: json: cannot unmarshal string into Go struct field User.id of type int64 already names it. SyntaxError.Offset points at the byte where parsing failed, which is enough to show a snippet. Custom UnmarshalJSON methods that wrap their error with %w keep the chain walkable with errors.As.

Common mistakes and compiler errors

Error or symptomCauseFix
Field missing from outputunexported fieldexport it, or add a method
json: unsupported type: chan inta field holds a non-marshalable typetag it out, or write a custom marshaler
json: cannot unmarshal string into Go struct field X.y of type inttype mismatch between JSON and Gofix the type, or use a custom UnmarshalJSON
null where a list was expectednil sliceinitialize to an empty slice
Boolean always false on the clientomitempty on a bool drops explicit falseuse *bool
Struct omitted unexpectedlyomitzero expected but not availableupgrade the language version, or use a pointer
Large id changes valuedecoded into interface{} as float64typed field or json.Number
Infinite recursion in MarshalJSONcalling json.Marshal on the same typemarshal a local type alias without methods
UnmarshalJSON has no effectvalue receiverpointer receiver
Unknown fields silently droppeddefault decoder behaviorDisallowUnknownFields
& becomes \u0026 in textHTML escaping in the encoderSetEscapeHTML(false)
time.Time fails to parseinput is not RFC 3339custom type with a layout

The design decisions worth making once per type are the null-versus-empty convention for slices, the pointer convention for optional scalars, and a custom type for money. Everything else — tags, embedded flattening, RawMessage for polymorphism — follows the shape of the data. A struct that round-trips its own output unchanged is the minimum bar, and a test that marshals, unmarshals, and compares is the cheapest way to enforce it.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.