Go Tutorial: JSON in Go
Speak the language of the web. Marshal structs to JSON, unmarshal JSON to structs, and build API-ready responses.
The language every API speaks
JSON is everywhere. Every web API sends and receives it. Every config file uses it. Every mobile app consumes it.
Go's `encoding/json` package handles it all — serialize a struct to JSON, parse JSON back into a struct, stream large JSON files, and customize exactly how your types are represented.
No third-party library needed. Twelve steps.
What you'll learn in this Go json in go tutorial
This interactive Go tutorial has 12 hands-on exercises. Estimated time: 22 minutes.
- What is JSON — JSON (JavaScript Object Notation) is a text format for structured data. Every web API uses it.
- Struct tags — control the JSON keys — By default, JSON keys match Go field names exactly. To use lowercase keys (which APIs expect), add struct tags:
- omitempty — skip zero values — `omitempty` tells the JSON encoder to skip a field if it is its zero value (empty string, 0, false, nil).
- Unmarshal — JSON to struct — `json.Unmarshal` parses JSON bytes and fills a Go struct.
- Unknown fields are ignored — When unmarshaling, Go silently ignores JSON keys that do not match any struct field. This is intentional — it lets you p…
- Nested structs in JSON — Nested Go structs become nested JSON objects automatically.
- Arrays and slices in JSON — Go slices become JSON arrays. JSON arrays become Go slices.
- Maps in JSON — `map[string]T` becomes a JSON object with dynamic keys.
- MarshalIndent — pretty print — `json.MarshalIndent` produces human-readable JSON with line breaks and indentation.
- Decoding from a stream — `json.NewDecoder` reads JSON from any `io.Reader` — an HTTP response body, a file, a string buffer.
- Custom marshaling — Sometimes the default marshaling is not what you want. Implement `MarshalJSON() ([]byte, error)` on your type to take fu…
- Build an API response builder — No starter code.
Go JSON in Go concepts covered
- The language every API speaks