A key-value pair is the line every YAML file is built from: a key, a colon, a space, then the value. A file holds one pair per line, and each key names the value beside it.
Every command and output on this page is real, run with yq 4.54.3 on macOS.
Syntax
Syntax
key: value
key: the name of the value. Each key appears only once in the same place.:followed by a space: separates the key from the value. The space is required.value: the value itself, such as text or a number. Text needs no quotes, even when it has spaces in it.
See Block Mappings in the YAML 1.2.2 specification.
Prerequisites
- yq, to check the YAML. Install it from yq’s install instructions.
The Example
A person’s name and city, saved in a file named person.yml.
Step 1: Write the YAML
person.yml
name: Asha
city: Pune
Step 2: Check It with yq
yq '.' reads the file and prints it back. If the YAML were broken, yq would stop with an error instead:
Terminal
yq '.' person.yml
Output
name: Asha
city: Pune
Step 3: Read One Value
Terminal
yq '.city' person.yml
Output
Pune
.city picks the value of the key city.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
No space after the colon: city:Pune | yq stops: Error: bad file 'person.yml': go-yaml load error in scanner (while scanning a simple key) at L2.C1-L3.C1: could not find expected ':' | Put a space after the colon: city: Pune |
The same key twice: city: Pune, then city: Mumbai | No error, but yq '.city' person.yml prints only Mumbai: the first value is lost | Give each key once |
FAQ
Can a value contain spaces?
Yes. city: New Delhi needs no quotes: yq '.city' person.yml prints New Delhi.
What is a mapping?
A group of key-value pairs, such as the two lines in person.yml. The YAML specification calls it a mapping.
Conclusion
Write each pair as a key, a colon, a space and the value, one pair per line, and give each key only once.
Additional Resources
- Block Mappings (YAML 1.2.2 specification)
- yq documentation
