Go JSON: Struct Tags and Marshal Internals

2025-01-30

Go maps JSON via structs and tags. Wrong tags and omitempty surprises cause most field-mismatch bugs in API work.

Struct tags

json:"name,omitempty"; unexported fields ignored.

type User struct {
  ID   int    `json:"id"`
  Name string `json:"name,omitempty"`
}

Unmarshal

Numbers in interface{} are float64; use json.Number or structs; DisallowUnknownFields for strict mode.

json.RawMessage

Delay inner parse for polymorphic payloads.

Marshal

Reflection-based; no func/channel; sonic/jsoniter for hot paths if needed.