Skip to main content
0 reactions

How to Write a List of Objects in YAML

Featured card for How to Write a List of Objects in YAML: a books.yml file with two books, Salt and Starlight at 12 and A Map of Quiet Places at 15, and a yq command that reads .books[1].title and prints A Map of Quiet Places.
How to Write a List of Objects in YAML

A list of objects is a list whose items each hold several keys, such as books with a title and a price. A dash starts each object, and the rest of its keys line up under its first key.

Every command and output on this page is real, run with yq 4.54.3 on macOS.

Syntax

SyntaxYAML
key:
  - field: value
    other_field: value
  - field: value
    other_field: value
  • - field: value: a dash and a space start a new object, with its first key on the same line.
  • other_field: value: the object’s next key, lined up under field, not under the dash.
  • Each new dash starts the next object.

Each object is a mapping inside a list: see Block Sequences (opens in a new tab) in the YAML 1.2.2 specification.

Prerequisites

The Example

Two books, each with a title and a price, in a file named books.yml.

Step 1: Write the YAML

books.ymlYAML
books:
  - title: Salt and Starlight
    price: 12
  - title: A Map of Quiet Places
    price: 15

Step 2: Check It with yq

yq reads the file and prints it back:

TerminalBash
yq '.' books.yml
OutputPlain text
books:
  - title: Salt and Starlight
    price: 12
  - title: A Map of Quiet Places
    price: 15

Step 3: Read a Value from One Object

TerminalBash
yq '.books[1].title' books.yml
OutputPlain text
A Map of Quiet Places

[1] picks the second book, because yq counts from 0, and .title picks its title.

Common Mistakes

MistakeWhat happensDo this instead
The second key lined up with the dash: price under -yq stops: Error: bad file 'books.yml': go-yaml load error in parser (while parsing a block collection) at L2.C3-L3.C3: did not find expected '-' indicatorLine up price under title
A dash before every key: - title: Salt and Starlight, then - price: 12No error, but each key becomes its own object: yq '.books[0]' books.yml prints only title: Salt and StarlightUse one dash per object

FAQ

Is a list of objects the same as an array of objects in JSON?

Yes, it’s the same structure. YAML calls the list a sequence and each object a mapping.

Conclusion

Start each object with a dash and a space, put its first key on the same line, and line up its other keys under the first one.

Additional Resources

0 comments