Skip to main content

Mapping

yaml.org 1.2.2 §10.2

key: value (block) | {key: value, ...} (flow)

A YAML mapping is an unordered collection of key-value pairs equivalent to a JSON object. Block style uses key: value pairs separated by newlines. Flow style uses JSON object syntax {key: value}. Keys are usually strings but can be any scalar, including integers.

Description

Mappings are the fundamental building block of YAML configuration. A mapping associates keys with values; keys are usually plain strings but the spec allows any node type as a key.

Block style writes each pair on its own line with the value indented under nested mappings. This is the dominant style for Kubernetes, Ansible, and GitHub Actions configuration.

Flow style uses {key: value} syntax, identical to JSON. Flow mappings are used inline for concise representations of simple objects.

Key ordering: the YAML 1.2.2 spec says mappings are unordered. In practice, most parsers preserve insertion order as an implementation detail (Python dict 3.7+, go-yaml, js-yaml all preserve order), but the spec does not require it.

Anchors and merge keys: a mapping can be anchored with & and referenced with *. The merge key << inserts all key-value pairs from the referenced mapping, enabling DRY configuration. Explicitly set keys override merged keys.

Duplicate keys: YAML 1.2 says duplicate keys in a mapping SHOULD be treated as an error. Most parsers accept duplicates and use the last value, but this is undefined behavior.

Complex keys: the ? indicator introduces a complex mapping key (e.g., a sequence as a key). This is rare in practice.

Examples

LabelValue
Block mappingmetadata: name: my-app namespace: default
Flow mappinglabels: {app: my-app, env: prod}
Empty mappingconfig: {}
Nested mappingspec: replicas: 3 selector: matchLabels: app: my-app
Anchor definitiondefaults: &defaults restartPolicy: Always imagePullPolicy: IfNotPresent
Merge anchorcontainer: <<: *defaults name: app image: app:1.0
Integer key1: one 2: two
Multi-document--- name: doc1 --- name: doc2

Common Gotchas

!

Key ordering is not guaranteed by spec – do not rely on YAML map order for logic; use sequences if order matters

!

Duplicate keys produce undefined behavior in 1.2 – most parsers silently use last-value-wins

!

The merge key << only merges one level deep; nested mappings are not deep-merged

!

A colon in a value must be quoted or followed by a non-space character – 'url: http://example.com' needs quoting

!

Boolean and null keys are valid in YAML: true: value, null: value. This surprises many parsers.

!

YAML anchors are per-document – they cannot reference nodes in a different YAML document separated by ---

!

Flow mappings {key: value} do not allow trailing commas in YAML 1.2

See Also