YAML Mappings
A YAML file is rarely used to describe a simple scalar. Most of the time, it describes a collection.
YAML collections can be a sequence or a mapping of elements.
In YAML, the collection is represented with proper sequence styles.
YAML Mappings
A mapping is a container consisting of key-value pairs where the keys must be unique.
YAML mappings are also known as associative arrays, hash tables, key: value pairs.
Mapping Styles
Like sequences, there are two ways to write a mapping.
Block Style version
In the block style, each key is written on a new line, followed by a colon (:
). The value can be placed either on the same line, or on the following line, indented one level:
person:
name: "Tom"
surname:
"Nolan"
age: 23
Flow Style version
In the flow style, the mapping is enclosed in curly brackets ({...}
), colons (followed by spaces) (:
) are used to separate keys and values, and key-value pairs are separated by commas (,
):
person: {name: "Tom", surname: "Nolan", age: 23}
Type of Mappings
We can classify mappings in four different types:
- Simple mapping
- Sequence mapping
- Nested mapping
- Mixed mapping
Simple Mapping
In simple mapping, we will provide a key in the first part, and then separate with a colon and space (,
):
---
host: tutorialreference-host
student: Tom
Sequence Mapping
We can map the value of the key in sequence.
---
student: Tom
hobbies:
- Maths
- ICT
---
student: Tom
hobbies: [Maths, ICT]
Nested Mapping
The mappings can be nested within each other.
---
host: tutorialreference-host
datacenter:
location: italy
cab: 10
cab_unit: 2
---
host: tutorialreference-host
datacenter: {location: italy, cab: 10, cab_unit: 2}
Mixed Mapping
In mixed mapping, we have both mappings and sequences as values.
---
student: Tom
details:
fatherName: Ryan
motherName: Lucy
more:
- Maths
- ICT
---
student: Tom
details: {fatherName: Ryan, motherName: Lucy}
more: [Maths, ICT]