🐹 Go (Golang) Intermediate

How does JSON encoding and decoding work in Go?

Answer

The encoding/json package serializes Go values to JSON and back. json.Marshal(v) encodes a Go value to a []byte of JSON. json.Unmarshal(data, &v) decodes JSON bytes into a Go value. Struct field names are used as JSON keys by default; customize them with struct tags: json:"user_name,omitempty". For streaming large JSON (HTTP bodies, files), prefer json.NewDecoder(r.Body).Decode(&v) and json.NewEncoder(w).Encode(v) which work with io.Reader/io.Writer and avoid loading the full payload into memory.