Skip to main content
0 reactions

How to Write a List in YAML

Featured card for How to Write a List in YAML: a basket.yml file with a fruits list of apple, banana and mango, each after a dash, a yq command that reads .fruits[1] and prints banana, and the note A dash, then a space.
How to Write a List in YAML

A list in YAML is a key followed by its items, one per line, each starting with a dash and a space. The items keep the order you write them in.

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

Syntax

SyntaxYAML
key:
  - item
  - item
  • key:: the name of the list, with nothing after the colon.
  • - : a dash and a space start each item.
  • item: the item’s value. All the items line up at the same indent.

See Block Sequences (opens in a new tab) in the YAML 1.2.2 specification.

Prerequisites

The Example

A basket of three fruits, in a file named basket.yml.

Step 1: Write the YAML

basket.ymlYAML
fruits:
  - apple
  - banana
  - mango

Step 2: Check It with yq

yq reads the file and prints it back:

TerminalBash
yq '.' basket.yml
OutputPlain text
fruits:
  - apple
  - banana
  - mango

Step 3: Read One Item

TerminalBash
yq '.fruits[1]' basket.yml
OutputPlain text
banana

[1] picks the second item: yq counts list items from 0.

Step 4: Count the Items

TerminalBash
yq '.fruits | length' basket.yml
OutputPlain text
3

length counts the items in the list.

Common Mistakes

MistakeWhat happensDo this instead
No space after the dash: -appleNo error, but the list is gone: yq '.' basket.yml prints fruits: -apple - banana - mango, one line of textPut a space after every dash

FAQ

Why does .fruits[1] print banana, not apple?

yq counts list items from 0, so apple is [0] and banana is [1].

Can a list hold numbers?

Yes. An item can be any value, such as text, a number or true, and each item is written after its own dash.

Conclusion

Write the key with nothing after its colon, then one item per line, each after a dash and a space, all at the same indent.

Additional Resources

0 comments