Skip to content

YAML – Flow Mappings

In YAML, data structures can be represented in two main styles: block style (using indentation) and flow style (more compact, often inline). Flow mappings are the flow style equivalent of dictionaries, objects, or associative arrays. They represent an unordered collection of key-value pairs, enclosed in curly braces {}.

Key characteristics of flow mappings:

  • Enclosed in curly braces: { key1: value1, key2: value2 }.
  • Key-value pairs are separated by a colon and a space (: ).
  • Multiple pairs are separated by a comma and a space (, ).
  • Keys must be unique within a mapping. Duplicate keys will typically result in an error or the last key overwriting previous ones, depending on the YAML parser.
  • Flow mappings are often used for simple, compact object representations, similar to JSON objects.

Here’s an example demonstrating flow mappings. We’ll define a user profile using this style:

# YAML 1.2
user_profile: { name: "John Doe", age: 30, city: "New York" }
# Flow mappings can also span multiple lines for readability
contact_details: {
email: "john.doe@example.com",
phone: "123-456-7890"
}
# Flow mappings can be nested
preferences: {
theme: "dark",
notifications: { email: true, sms: false }
}

The equivalent JSON representation of the above YAML would be:

{
"user_profile": {
"name": "John Doe",
"age": 30,
"city": "New York"
},
"contact_details": {
"email": "john.doe@example.com",
"phone": "123-456-7890"
},
"preferences": {
"theme": "dark",
"notifications": {
"email": true,
"sms": false
}
}
}

Notice how flow mappings directly translate to JSON objects. They are particularly useful when you need a compact representation or when embedding a small map within a larger structure, perhaps even within a flow sequence.

When to Use Flow Mappings vs. Block Mappings

Section titled “When to Use Flow Mappings vs. Block Mappings”

Use flow mappings for:

  • Simple, small objects where inline representation is clearer.
  • Data that closely resembles JSON objects.
  • Embedding small mappings within other flow structures or even as values in block structures.

Use block mappings (indentation-based) for:

  • Larger, more complex objects where readability benefits from explicit indentation.
  • When multi-line string values are involved, as block scalars integrate more naturally with block mappings.

Choosing between them often comes down to readability and the complexity of the data. Many YAML documents use a combination of both styles.