Skip to main content
0 reactions

How to Write a Key-Value Pair in YAML

Featured card for How to Write a Key-Value Pair in YAML: a person.yml file with name: Asha and city: Pune, a yq command that reads .city from it and prints Pune, and the notes A space after the colon and Each key once.
How to Write a Key-Value Pair in YAML

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

SyntaxYAML
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 (opens in a new tab) in the YAML 1.2.2 specification.

Prerequisites

The Example

A person’s name and city, saved in a file named person.yml.

Step 1: Write the YAML

person.ymlYAML
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:

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

Step 3: Read One Value

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

.city picks the value of the key city.

Common Mistakes

MistakeWhat happensDo this instead
No space after the colon: city:Puneyq 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: MumbaiNo error, but yq '.city' person.yml prints only Mumbai: the first value is lostGive 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

0 comments