liveBook · Manning

Encoding/json

As explained in Learn Go with Pocket-Sized Projects

encoding/json is Go's standard-library package for encoding and decoding JSON data.

encoding/json is Go’s standard-library package for converting structured JSON data to and from Go values. It supports json.Decoder and json.Unmarshal for decoding, plus json.Encoder and json.Marshal for encoding. section 3.5

Listing 3.4 bookworm.go: Bookworm and Book structures
// A Bookworm contains the list of books on a bookworm's shelf.
type Bookworm struct {
    Name  string `json:"name"` #1
    Books []Book `json:"books"` #2
}

// Book describes a book on a bookworm's shelf.
type Book struct {
    Author  string `json:"author"`
    Title   string `json:"title"`
}

Define exported Go structures whose fields match the JSON shape, using tags such as `json:"name"` and `json:"books"` to map field names. section 3.1.3

A practical file-decoding workflow:

  • Keep destination fields exported so the decoder can write to them; store test JSON under `testdata`. section 3.1.3 section 3.5

Loading bookworms

Calling `loadBookworms("testdata/bookworms.json")` returns bookworms and their books, or prints an error and exits. Running `go run .` produces entries such as Fadi with Margaret Atwood’s The Handmaid's Tale and Sylvia Plath’s The Bell Jar.

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains structure matching, tags, exported fields, streaming decoding, and errors, while deferring detailed HTTP response decoding.
Examples
Demonstrates decoding a bookworm-and-books JSON file into tagged Go structures and printing the resulting slice.
What it assumes
Assumes Go structures, slices, and file handling; teaches JSON field tags and the exported-field requirement.
What you can do after
Apply via encoding/json to decode files into exported, tagged Go structures and handle failures returned by the decoder.
How it connects
Connects JSON with Go structs, slices, maps, io.Reader, file handling, and HTTP response decoding.

Also explained in

Compare how 2 books explain encoding/json →

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.