encoding/json
encoding/json converts Go values to JSON and back. Marshal/Unmarshal work on bytes. Encoder/Decoder work on streams. Struct tags control names.
Detailed Explanation
json.Marshal(v) walks v with reflection and returns []byte. json.Unmarshal(data, &v) fills a pointer. Maps become objects, slices become arrays, nil slices and maps become null (unless you use empty composites). Numbers unmarshal into float64 when the target is any.
Use a pointer target. Unmarshal into a non-pointer fails. Into a nil *T it allocates. Into an existing struct it merges exported fields and leaves others.
Streaming. json.NewDecoder(r.Body) for request bodies avoids buffering the whole payload if you only need one value — it still reads the value fully. NewEncoder(w).Encode(v) writes a value plus a newline. Prefer these in handlers over ReadAll plus Unmarshal when the body is large.
useNumber and precision. JSON numbers are not Go int. A large ID in map[string]any becomes float64 and can lose bits. Decoder.UseNumber() keeps json.Number (a string). Better: unmarshal into a struct with int64 fields.
Custom types. MarshalJSON/UnmarshalJSON methods override the default. They must not infinitely call Marshal on the same type; use an alias (type aux T) or a DTO.
What it costs. Reflection is slower than a hand-written encoder and fast enough for typical APIs. Allocation of []byte on every Marshal shows up in profiles; Encoder to a bytes.Buffer from a pool can help. Correctness costs more: null vs [], number precision, and unknown fields.
Code Examples
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
func main() {
b, _ := json.Marshal(User{ID: 1, Name: "Ada"})
fmt.Println(string(b))
var u User
_ = json.Unmarshal(b, &u)
fmt.Println(u.Name)
}func decodeBody(r io.Reader) (User, error) {
var u User
err := json.NewDecoder(r).Decode(&u)
return u, err
}Common Gotchas
`any` numbers are `float64`
64-bit IDs can round. Use structs.
`nil` slice marshals as `null`, empty slice as `[]`
APIs often want `[]`.
`Encode` writes a trailing newline
tests that compare bytes should allow it or use `Marshal`.
`Unmarshal` without a pointer does not fill your value
`Unmarshal` without a pointer does not fill your value