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.

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,omitemptyomits zero values. omitemptydoes not omit a zero struct, a zerotime.Time, or a zero-length array — use a pointer oromitzero(Go 1.24+) for those.,stringencodes a number or boolean as a JSON string; on astringfield it double-encodes.- Embedded structs are flattened into the parent object; an embedded field with a tag becomes a nested object.
Unmarshalignores unknown fields by default;Decoder.DisallowUnknownFieldsturns a typo into an error.- Numbers decode into
uint64/int64fields exactly, but intointerface{}asfloat64, 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
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"`
}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.
| Tag | Effect |
|---|---|
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 field | embedding is disabled unless a name is given |
Comparison of JSON boundaries
| Source | Decode target | Precision | Unknown fields | Notes |
|---|---|---|---|---|
Struct field int64 | exact | exact | ignored | best for ids |
Struct field float64 | exact as float | exact until 2^53 | ignored | money problems |
interface{} | float64 everywhere | loses digits past 2^53 | kept | use json.Number |
json.Number | string-backed | exact | n/a | decode then parse |
map[string]any | nested map/[]any | same as interface{} | kept | flexible, untyped |
json.RawMessage | deferred bytes | exact | deferred | polymorphic 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
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 []:
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
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
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
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) // 9007199254740993The 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
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 symptom | Cause | Fix |
|---|---|---|
| Field missing from output | unexported field | export it, or add a method |
json: unsupported type: chan int | a field holds a non-marshalable type | tag it out, or write a custom marshaler |
json: cannot unmarshal string into Go struct field X.y of type int | type mismatch between JSON and Go | fix the type, or use a custom UnmarshalJSON |
null where a list was expected | nil slice | initialize to an empty slice |
Boolean always false on the client | omitempty on a bool drops explicit false | use *bool |
| Struct omitted unexpectedly | omitzero expected but not available | upgrade the language version, or use a pointer |
| Large id changes value | decoded into interface{} as float64 | typed field or json.Number |
Infinite recursion in MarshalJSON | calling json.Marshal on the same type | marshal a local type alias without methods |
UnmarshalJSON has no effect | value receiver | pointer receiver |
| Unknown fields silently dropped | default decoder behavior | DisallowUnknownFields |
& becomes \u0026 in text | HTML escaping in the encoder | SetEscapeHTML(false) |
time.Time fails to parse | input is not RFC 3339 | custom 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 toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
Go init Function: Package Initialization Order, Imports, and Side Effects
What runs before main, the order across imports and files, why init cannot return an error, and the sync.Once replacement that can be tested.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.