Capstone 2: JSON output

A table is for a person and JSON is for a script. The command already prints the table, and the -json flag on list switches to one JSON object per task. One object per line is the format a shell tool reads: while read, jq and a Go scanner all consume it without knowing the whole set.

The task on the wire

The struct is the same one the file uses, with the id, title and done flag, and the due date as a pointer so omitempty drops it. The names are lower case and stable: a script that reads done and a file that stores it agree, which is the reason not to keep a second DTO for a command this size.

type Task struct { ID int `json:"id"` Title string `json:"title"` Done bool `json:"done"` Due *time.Time `json:"due,omitempty"` }

A task without a due date has no due key at all, and a task with one has the RFC3339 form of midnight UTC. A script that wants a date and not a timestamp takes the first ten characters, and a program that parses it uses time.RFC3339; the page of lesson 86 has both.

One object per line

ListJSON reads the store once and encodes each task into the writer, which is a json.Encoder per call rather than a buffer. The encoder appends a newline after each value, which is exactly the line format, and an error stops the loop with the operation name.

func (c *Commands) ListJSON() ([]Task, error) { tasks, err := c.Store.All() if err != nil { return nil, Wrap("list", err) } enc := json.NewEncoder(c.Out) for _, task := range tasks { if err := enc.Encode(task); err != nil { return nil, Wrap("encode", err) } } return tasks, nil }

The JSON is not wrapped in an array, so a consumer can process a line the moment it arrives and a huge list never has to fit in memory. A program that needs one document can read the lines and build the array itself, or use the file form of the store, which is a single object.

The run

The two tasks from the previous lessons are in the demo file. The command prints two lines, one per task, and the shell status is 0.

TASKS_FILE=/tmp/tasks-demo.json ./bin/tasks list -json

{"id":1,"title":"buy milk","done":false,"due":"2026-11-20T00:00:00Z"}
{"id":2,"title":"write lesson","done":false}

The first task has the due key and the second does not, and both lines are complete objects. A pipe into jq -c 'select(.done)' would print the done tasks, and a Go program reads the same lines with a decoder in a loop, which is the streaming lesson 89.

Reading it from a script

A shell loop over the output is one line per task and needs no parser. A Go consumer decodes into the model type from the same module, or into a local struct with the three fields it wants; the second is the better choice for a script that outlives the tool, because it does not depend on the package. A field that is added later is ignored by both, which is the forward compatibility the tags give for free.

Two details keep the format usable. The order of the fields is the struct order, so a diff is stable, and the numbers are JSON numbers, so id can be compared without parsing a string. A timestamp stays a string in RFC3339, which is the one format every language parses.

JSON is the script API

The table is the human API and the JSON is the script API, and both come from the same read. The flag changes the formatter, not the data, which is why the command layer has a List and a ListJSON and no branch inside either. The next lesson measures the store, and the last one releases the command.

Exercises

  1. Add a -json flag to add that prints the created task as one object. Which encoder do you reuse, and what does the table print?
  2. Pipe the output into jq -c 'select(.done)' and then into wc -l. What does the count mean, and how does an empty result look?
  3. Change the due date to a string field formatted in the model and compare the tags. What does the parser lose, and what does the script gain?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What shape does list -json write?

    Answer

    One JSON object per line

    A script reads it line by line.

  2. Why is the due date a pointer?

    Answer

    omitempty drops a nil pointer and not a zero struct

    A task without a due date has no key.

  3. What adds the newline between objects?

    Answer

    json.Encoder.Encode

    The encoder ends each value with a newline.

  4. Why not wrap the tasks in an array?

    Answer

    A consumer processes a line at once and the list need not fit in memory

    It is the streaming shape.

  5. What format does the due timestamp use?

    Answer

    RFC3339

    encoding/json uses RFC3339 for time.Time.

  6. How does a script read the output?

    Answer

    One line at a time with a JSON parser

    A shell loop or jq does it.

  7. Why is a consumer struct better than the model type?

    Answer

    A script that outlives the tool does not depend on the package

    The wire shape is the contract.

  8. What happens to an unknown field in a consumer?

    Answer

    It is ignored, which is forward compatible

    The decoder ignores it by default.

  9. Why is the field order stable?

    Answer

    It follows the struct order

    A diff stays readable.

  10. What does -json change?

    Answer

    The formatter, not the data

    ListJSON reads the same store.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image