Guide
How to write YAML lists and objects at the correct level
Learn to combine YAML sequences and mappings, align list markers, and verify the equivalent JSON structure.
by Tools in a Tab · Published on · Reviewed on
Short answer
A YAML list is a sequence whose items begin with -. An object is a mapping of
keys and values separated by :. To create a list of objects, align every list
marker and place the additional properties of each item at the same level as
the first key after its marker.
A list of simple values
ports:
- 80
- 443
- 8080
The ports key contains a sequence of three numbers. The markers occupy the
same column because all three items are siblings. Its JSON equivalent is:
{
"ports": [80, 443, 8080]
}
A list of objects
servers:
- name: api-1
ip: 192.0.2.10
active: true
- name: api-2
ip: 192.0.2.11
active: false
Each marker starts one sequence item. name, ip, and active belong to the
same server mapping. The second marker returns to the column of the first and
starts the next item.
The YAML to JSON converter shows two objects inside
the servers array. Always inspect the resolved result: valid YAML can still
represent a different tree from the one you intended.
The most common level error
This fragment moves active outside the expected structure:
servers:
- name: api-1
ip: 192.0.2.10
active: true
The problem is structural, not cosmetic. active is no longer aligned with
the object’s properties, and a processor may reject the document because it
expected another sequence item at that point.
A similarly dangerous variant aligns a property with the list marker:
servers:
- name: api-1
ip: 192.0.2.10
The ip field does not belong to the object begun after the marker. Compare
columns rather than the apparent amount of space between words.
Mappings containing lists and lists containing mappings
Structures can alternate as deeply as the format and application allow:
service:
name: api
targets:
- host: db-1
roles:
- read
- write
- host: db-2
roles:
- read
Read from the outside inward: service is a mapping, targets is a list, each
target is a mapping, and roles is another list.
Checklist
- Identify each expected node type: mapping, sequence, or scalar.
- Align all markers that belong to the same list.
- Align sibling properties inside every mapping.
- Never use tabs to define YAML indentation.
- Convert the sample to JSON and count objects, arrays, and levels.
- Compare the resulting tree with the application’s schema.
Section 8.2 of YAML 1.2.2
defines block sequences with - indicators and mappings with key/value pairs.
Indentation determines which collection owns each node, so changing a column
changes the data structure.