Riferimento completo alla sintassi YAML 1.2 con esempi. Copre scalari, sequenze, mappature, ancore, stringhe multiriga, tag e insidie comuni.
Plain unquoted string — most common
name: John Doe
Single-quoted: no variable or escape processing
path: '/usr/bin/node'
Double-quoted: supports escape sequences (\n, \t, etc.)
message: "Hello\nWorld"
Whole number (base 10)
port: 8080
Floating point number
threshold: 0.95
Boolean value — use only true/false (YAML 1.2)
debug: false
Null / absence of value
response: null
ISO 8601 date format
created: 2024-01-15T10:30:00Z
Single-line comment. No multi-line comment syntax.
# This is a comment key: value # inline comment
Force value to be treated as a specific type
port: !!str 8080 # string '8080' not int
Key-value pairs — indented block style
app: name: myapp port: 3000
Inline map — equivalent to block style
env: {NODE_ENV: prod, PORT: 8080}List of items — block style with dash+space
fruits: - apple - banana - cherry
Inline list — equivalent to block style
ports: [80, 443, 8080]
List where each item is a map
users:
- name: Alice
role: admin
- name: Bob
role: userArbitrarily deep nesting
database:
primary:
host: db1.example.com
port: 5432Merge the keys of a referenced mapping into current map
defaults: &defaults color: blue button: <<: *defaults text: Submit
Preserves newlines exactly as written
script: | #!/bin/bash echo "hello" exit 0
Newlines folded into spaces (great for long descriptions)
description: > This is a very long description that will be joined into one line.
Literal block, strip all trailing newlines
prompt: |- Enter value:
Literal block, keep all trailing newlines
template: |+ line1
Folded block, strip trailing newlines
message: >- This folds into one line no trailing newline
Assigns an anchor (label) to the current node
base: &base image: node:18 restart: always
References (copies) an anchored node
service1: <<: *base name: api service2: <<: *base name: worker
Anchor a scalar value to reuse it
read_timeout: &rto 30 write_timeout: *rto connect_timeout: *rto
Anchor a list
primary_colors: &colors - red - blue text_colors: *colors
Explicitly declare YAML version (optional, rarely needed)
%YAML 1.2 --- name: myapp
Marks the start of a YAML document. Required if using directives.
--- kind: Deployment --- kind: Service
Marks the end of a YAML document. Optional but useful.
--- debug: true ...
Multiple YAML docs in one file (stream)
Used in Kubernetes multi-resource files
Base64-encoded binary data
icon: !!binary | iVBORw0KGgo=
Indentation MUST use spaces only — never tabs
# WRONG: parent: \tchild: value # RIGHT: parent: child: value
Values containing ': ' (colon+space) must be quoted
# WRONG: url: http://example.com # RIGHT: url: "http://example.com"
1.0 parses as float! Quote or tag it to keep as string
version: '1.0' # string version: 1.0 # float
YAML 1.1 parses yes/no/on/off as booleans — quote to use strings
# YAML 1.1 (PyYAML): on: true # 'on' is boolean true! # Safe: always quote on: 'on'
Trailing spaces in keys are included in the key string
"key " (with space) != "key" — trim carefully
Duplicate keys — behavior is parser-specific (usually last wins). Treat as error.
Use a YAML linter to detect duplicate keys
| Funzionalità | YAML | JSON |
|---|---|---|
| Commenti | Yes: # comment | Non supportato |
| Virgolette richieste | Opzionale per le stringhe | Richieste per le stringhe |
| Anchors/aliases | Yes: &anchor / *alias | Non supportato |
| Stringhe multi-linea | Yes: | and > blocks | Escaped \n only |
| Tab per l'indentazione | Solo spazi | Entrambi |
| È un superset di JSON | Tutto JSON è YAML valido | - |
| Leggibilità umana | Molto alta | Medio |
| Disponibilità del parser | Alta | Molto alta |
Importante: Molti parser YAML usano ancora YAML 1.1 per impostazione predefinita (PyYAML di Python, Psych di Ruby in alcune versioni).
YAML è un superset di JSON — qualsiasi JSON valido è YAML valido. YAML è progettato per essere più leggibile dagli esseri umani con supporto per commenti, stringhe multiriga e ancore/alias. JSON è più rigoroso, più veloce da analizzare e universalmente supportato. Usa YAML per i file di configurazione e JSON per le API e lo scambio di dati.
In YAML 1.1 (usato da molti parser tra cui PyYAML), 'on', 'off', 'yes', 'no' sono valori booleani validi. Questo può causare bug quando vengono usati come stringhe semplici (es. in Ansible). YAML 1.2 ha risolto questo problema — solo 'true' e 'false' sono booleani. Soluzione: racchiudete sempre questi valori tra virgolette ('yes', 'no') se volete usarli come stringhe.
Usa il literal block scalar (|) per preservare le interruzioni di riga: ogni riga nel blocco diventa una vera interruzione di riga nella stringa. Usa il folded block scalar (>) per piegare le interruzioni di riga in spazi: ottimo per i paragrafi lunghi. Entrambi supportano indicatori di chomping opzionali (- per rimuovere le interruzioni di riga finali, + per mantenerle tutte).
YAML usa spazi per l'indentazione — mai tabulazioni. Tutte le chiavi sorelle devono essere allo stesso livello di indentazione. Mescolare tabulazioni e spazi causerà sempre errori. Soluzioni comuni: attiva l'impostazione 'sostituisci le tabulazioni con spazi' nel tuo editor, usa un linter (yamllint), assicura una larghezza di indentazione coerente (2 o 4 spazi) in tutto il file.