Site icon JD Bots

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

Syntax

key: value

See Block Mappings 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.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

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

Exit mobile version