Last updated

Lesson 3: Maps

root mapping nodes

In terms of foundation, most YAML you'll encounter has a root mapping node. In this context, "root" means it's at the top-level (root level) of the file structure. "Mapping node" means it's a collection of data represented as a map. A map is composed of one or more unordered nodes of keys-values. The keys are separated from values by a colon and a space (:), like this example:

ExampleKey: ExampleValue
AnotherKey: AnotherValue

The equivalent in JSON is called an object.

{
   "ExampleKey": "ExampleValue",
   "AnotherKey": "AnotherValue"
}

A map is a set of unordered key-value pairs:

Car: red
Hair: gray

Because maps are unordered key-value pairs, the previous map is the same as the following map:

Hair: gray
Car: red

A map must have unique keys. The keys and values are case sensitive.

hair: gray
Hair: gray
hair: gray
hair: gray

Flow maps

Maps can be written in a more compact way with commas separating the map items.

{Hair: gray, Car: red}

This is the same as normal map style.

Hair: gray
Car: red

Flow maps are less common because they're more difficult to read.

Common problems with YAML maps (missing a space)

The keys are separated by a colon and a space

If the space is missing, the YAML is broken.

Car:red

To fix it, add a space.

Car: red

Exercise 3.1: Spot the key(s) with the problem

Hair: gray
Car: red
Grass:green
Sky:blue
See answer

The Grass and Sky keys were missing a space after the colon.

The correct YAML is:

Hair: gray
Car: red
Grass: green
Sky: blue

Looking ahead: The values (and keys) used in the example are all scalars (atomic data types). The next lesson is about scalars (the most common type of value).