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
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
- yq, to check the YAML. Install it from yq’s install instructions (opens in a new tab).
The Example
A person whose address has its own city and PIN code, in a file named person.yml.
Step 1: Write the YAML
name: Asha
address:
city: Pune
pin: 411001
Step 2: Check It with yq
yq reads the file and prints it back, indents included:
yq '.' person.yml
name: Asha
address:
city: Pune
pin: 411001
Step 3: Read a Nested Value
yq '.address.city' person.yml
Pune
.address.city goes into address, then picks city.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
One child indented more than the others: three spaces before pin | yq stops: Error: bad file 'person.yml': go-yaml load error in scanner at L4.C7: mapping values are not allowed in this context | Give every child of address the same indent |
| A tab instead of spaces | yq 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 token | Indent 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 Pune | Indent 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
- Indentation Spaces (opens in a new tab) (YAML 1.2.2 specification)
- Block Mappings (opens in a new tab) (YAML 1.2.2 specification)
- Traverse (Read) (opens in a new tab) (yq documentation)
0 comments