YAML Flow Style vs Block Style: When to Use Each
Understand the difference between YAML flow style (inline JSON-like syntax) and block style (indented format). Learn when each style is appropriate and how formatters convert between them.
Detailed Explanation
YAML Flow Style vs Block Style
YAML supports two fundamental notations for representing data structures: block style (indentation-based) and flow style (inline, JSON-like). Understanding both is essential for reading and writing YAML effectively.
Block Style
Block style uses indentation to represent structure:
database:
host: localhost
port: 5432
credentials:
username: admin
password: secret
options:
- ssl
- compression
This is the most common YAML style and is preferred for configuration files because of its readability.
Flow Style
Flow style uses curly braces for mappings and square brackets for sequences:
database: {host: localhost, port: 5432, credentials: {username: admin, password: secret}, options: [ssl, compression]}
Flow style is compact but becomes hard to read for complex nested structures.
Mixing Styles
YAML allows mixing flow and block styles within the same document:
servers:
- name: web-1
tags: [production, frontend]
config: {memory: 4096, cpu: 2}
- name: web-2
tags: [production, backend]
config: {memory: 8192, cpu: 4}
This hybrid approach is common and idiomatic — short, simple collections use flow style while complex structures use block style.
When to Use Flow Style
- Short lists —
tags: [web, api, v2] - Simple key-value pairs —
limits: {cpu: "500m", memory: "128Mi"} - Single-line readability — When the entire collection fits on one line without wrapping
- Embedding in block context — Flow collections inside block-style documents
When to Use Block Style
- Complex nested structures — Anything deeper than one level
- Long values — When values would cause line wrapping
- Configuration files — Block style is the convention for config files
- Documents that will be hand-edited — Block style is easier to modify
Formatter Options
Most YAML formatters offer options to control flow vs block style:
- Always block — Convert all flow collections to block style
- Always flow — Convert all block collections to flow style (minification)
- Preserve — Keep the author's original choice
- Smart — Use flow style for short collections, block style for complex ones
Use Case
Understanding flow vs block style is crucial when configuring YAML linters and formatters for a team. Some teams prefer pure block style for maximum readability, while others allow flow style for short collections. A formatter that can convert between styles helps enforce team conventions and can simplify YAML files that use overly verbose block style for simple values.