Skip to main content
0 reactions

How to Nest Keys in YAML with Indentation

Featured card for How to Nest Keys in YAML with Indentation: a person.yml file where address holds city: Pune and pin: 411001 indented under it, a yq command that reads .address.city and prints Pune, and the note Spaces, never tabs.
How to Nest Keys in YAML with Indentation

To put keys inside another key in YAML, write the parent key with nothing after its colon, then indent its keys on the lines below. The indent is what tells YAML which keys belong together.

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

Syntax

SyntaxYAML
parent:
  child: value
  other_child: value
  • parent:: a key with nothing after the colon. The indented keys below it belong to it.
  • The indent: the spaces before each child key. Every child of the same parent has the same number of them, and two is common.
  • Spaces only: YAML doesn’t allow tabs for indentation.

See Indentation Spaces (opens in a new tab) in the YAML 1.2.2 specification.

Prerequisites

The Example

A person whose address has its own city and PIN code, in a file named person.yml.

Step 1: Write the YAML

person.ymlYAML
name: Asha
address:
  city: Pune
  pin: 411001

Step 2: Check It with yq

yq reads the file and prints it back, indents included:

TerminalBash
yq '.' person.yml
OutputPlain text
name: Asha
address:
  city: Pune
  pin: 411001

Step 3: Read a Nested Value

TerminalBash
yq '.address.city' person.yml
OutputPlain text
Pune

.address.city goes into address, then picks city.

Common Mistakes

MistakeWhat happensDo this instead
One child indented more than the others: three spaces before pinyq stops: Error: bad file 'person.yml': go-yaml load error in scanner at L4.C7: mapping values are not allowed in this contextGive every child of address the same indent
A tab instead of spacesyq stops: Error: bad file 'person.yml': go-yaml load error in scanner (while scanning for the next token) at L3.C1: found character that cannot start any tokenIndent with spaces
No indent under address:No error, but city is no longer inside address: yq '.address.city' person.yml prints null, and yq '.city' person.yml prints PuneIndent the child keys

FAQ

How many spaces should I use?

Any number, as long as every child of the same parent uses the same one. Two spaces is the most common choice.

How deep can I nest keys?

As deep as you need. Each level is indented further under its parent, and yq reads it with one more key in the path, as .address.city does.

Conclusion

Write the parent key with nothing after its colon, indent its child keys with spaces, and give every child of the same parent the same indent.

Additional Resources

0 comments