04 / 04

Explain how encoding/json marshaling works with struct tags and custom marshalers.

encoding/json uses struct tags to control JSON field names and behavior. Implement json.Marshaler and json.Unmarshaler interfaces for custom serialization logic.

Struct tags and custom marshalers
Common pitfalls
  1. 1

    Unexported fields are silently ignored — always export fields you want serialized

  2. 2

    interface{} numbers unmarshal as float64 by default — use UseNumber() for large integers

  3. 3

    omitempty omits zero values: 0, false, "", nil — careful with intentional zero values

  4. 4

    Anonymous embedded structs promote their fields to the parent — useful but can cause field collisions

  5. 5

    json.RawMessage allows deferring or passing through raw JSON without parsing