Working with JSON in Go
Encode Go structs to JSON with struct tags and omitempty, and decode JSON safely with Unmarshal, NewDecoder and unknown field checks.
encoding/json turns Go values into JSON and back. This section covers the rules that decide which fields appear, and how to decode input strictly.
Encoding JSON and Struct Tags
type Order struct {
ID int `json:"id"`
Notes string `json:"notes,omitempty"`
}
Only exported fields are encoded. Tags set names, omitempty drops zero values, and - hides a field.
Decoding JSON
json.Unmarshal for data in memory, json.NewDecoder for HTTP bodies and other streams, plus DisallowUnknownFields and pointer fields for strict input.
Silent by default:
Lowercase fields, misspelled keys and missing values do not produce errors. Most JSON bugs in Go come from expecting an error that never happens.
Summary
Export the fields you need, name them with tags, and decode untrusted input with a strict json.Decoder.
Encoding JSON and Struct Tags in Go
Turn Go structs into JSON with json.Marshal, control field names with struct tags, use omitempty and "-", and fix fields that do not show up.
Decoding JSON in Go
Parse JSON into Go structs with json.Unmarshal and json.NewDecoder, reject unknown fields, detect missing values, and decode HTTP request bodies safely.