Decode reads JSON from a decoder's input and writes the result into a supplied Go value. For structured data, define matching structs with JSON tags, expose fields, create the destination value, and pass its pointer so the decoder can populate it. section 3.1.3
A practical JSON-decoding sequence:
- Open the input file and defer closing it. section 3.1.3
- Declare the destination with the shape of the JSON, such as a slice of Bookworm values. section 3.1.3
- Call json.NewDecoder(file).Decode(&destination) and return any decoding error. section 3.1.3
Decode bookworms
loadBookworms opens bookworms.json, decodes it into []Bookworm, returns the populated slice, and reports failures. Running the program prints each bookworm and shelf. section 3.1.3
Listing 3.5 bookworm.go: JSON decoding in loadBookworms()
var bookworms []Bookworm #1
// Decode the file and store the content in the value bookworms.
err = json.NewDecoder(f). #2
Decode(&bookworms) #3
if err != nil { #4
return nil, err
}
The listing shows the essential destination declaration, pointer passed to Decode, and immediate error check. section 3.1.3














