Complete Guide to YAML Configuration Syntax
Introduction to YAML
YAML (YAML Ain't Markup Language) is a human-readable data serialization format designed for configuration files and data exchange. Unlike JSON, YAML emphasizes readability and offers a more concise syntax for representing complex data structures.
Basic Rules
- Case-sensitive syntax
- Hierarchy defined by indentation
- Only spaces allowed for indentation (tabs are forbidden)
- Alignment determines nesting level
- Comments start with
#
YAML supports three primary data types:
- Mappings: Key-value pairs (objects/hashes/dictionaries)
- Sequences: Ordered lists (arrays)
- Scalars: Single atomic values
Mapping Syntax
Key-value pairs use a colon separator:
creature: felineParsed result:
{ creature: 'feline' }Inline mapping notation:
user: { name: Alice, role: admin }Parsed result:
{ user: { name: 'Alice', role: 'admin' } }Sequence Syntax
List items begin with a hyphen:
- Lion
- Tiger
- LeopardParsed result:
[ 'Lion', 'Tiger', 'Leopard' ]Nested sequences require indentation:
-
- Lion
- Tiger
- LeopardParsed result:
[ [ 'Lion', 'Tiger', 'Leopard' ] ]Inline array notation:
predators: [Lion, Tiger]Parsed result:
{ predators: [ 'Lion', 'Tiger' ] }Composite Structures
Mappings and sequences can be combined:
frameworks:
- Django
- Flask
- FastAPI
endpoints:
auth: /api/login
data: /api/fetch
users: /api/usersParsed result:
{ frameworks: [ 'Django', 'Flask', 'FastAPI' ],
endpoints: {
auth: '/api/login',
data: '/api/fetch',
users: '/api/users'
}
}Scalar Types
YAML supports various scalar data types including strings, booleans, integers, floats, null values, timestamps, and dates.
Numeric values:
pi: 3.14159
count: 42Boolean values:
enabled: true
disabled: falseNull values use tilde:
optional: ~Timestamps in ISO8601 format:
created: 2023-06-15T14:30:00.00ZDate values:
birthdate: 1990-12-25Type coercion with double exclamation marks:
stringNum: !!str 456
stringBool: !!str falseParsed result:
{ stringNum: '456', stringBool: 'false' }String Handling
Strings without special characters need no quotes:
greeting: Hello WorldStrings containing colons or special characters require quotes:
instruction: "Value: important"Single quotes preserve literal characters:
literal: 'Line1\nLine2'Double quotes interpret escape sequences:
escaped: "Line1\nLine2"Single quote escaping within single quotes:
apostrophe: 'It''s working'Multi-line strings fold into single line:
description: This is a
multi-line
text blockLiteral block scalar preserves newlines with pipe:
content: |
First line
Second line
Third lineFolded block scalar converts newlines to spaces:
summary: >
This entire block
becomes one line
of textBlock chomping indicators:
clip: |
Text
strip: |-
Text
keep: |+
TextAnchors and Aliases
Use anchors (&) and aliases (*) to reuse content:
default_settings: &defaults
timeout: 30
retries: 3
production:
env: prod
<<: *defaults
staging:
env: stage
<<: *defaultsThe merge key (<<) inserts the anchored content. Equivalent expanded form:
production:
env: prod
timeout: 30
retries: 3Array element reuse:
- &lead Developer1
- Developer2
- Developer3
- *leadParsed result:
[ 'Developer1', 'Developer2', 'Developer3', 'Developer1' ]JavaScript Function and Regex Serialization
JS-YAML can serialize JavaScript functions and regular expressions:
# config.yaml
handler: function () { return 42; }
pattern: /\d+/Loading YAML in Node.js:
const yaml = require('js-yaml');
const fs = require('fs');
try {
const data = yaml.load(fs.readFileSync('./config.yaml', 'utf8'));
console.log(data);
} catch (err) {
console.error(err);
}Serializing objects back to YAML:
const yaml = require('js-yaml');
const fs = require('fs');
const config = {
handler: function () { return 42; },
pattern: /\d+/
};
try {
fs.writeFileSync('./output.yaml', yaml.dump(config), 'utf8');
} catch (err) {
console.error(err);
}