liveBook · Manning

Decode

As explained in Learn Go with Pocket-Sized Projects

Decode is a JSON decoder method that reads JSON input and stores the decoded result in a supplied Go value.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains JSON tags, exported fields, slice destinations, pointer passing, and errors, while deferring explicit streaming.
Examples
Uses bookworms.json, Bookworm and Book structures, loadBookworms(), and printed decoded records.
What it assumes
Assumes Go structures, slices, files, and errors; teaches JSON tags and pointer destinations in context.
What you can do after
Apply it via encoding/json to decode a file into a typed slice and return or report errors.
How it connects
Connects JSON decoding with encoding/json, structs, slices, pointers, exported fields, and error handling.

Also explained in

Compare how 15 books explain decode →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.