1. YAML for People Who Know JSON
A superset that giveth whitespace and taketh away your sanity
You already know JSON cold. Objects, arrays, strings, numbers, booleans, null.
No comments, no trailing commas, quote every key, escape every control character.
It is a small, boring, gloriously unambiguous language, and that is exactly why it
won as the interchange format of the internet.
YAML is what happens when you take JSON and optimise the other direction — for a human typing a config file by hand. The single most useful fact about YAML, and the one this whole article hangs off of, is this:
The through-line
YAML 1.2 is a superset of JSON. Every valid JSON document is (with a caveat we'll get to) already a valid YAML document that parses to the same data. So you don't have to learn YAML from scratch — you learn what YAML lets you drop, what it lets you add, and where those additions quietly bite.
We'll start from JSON you can already read, peel away the punctuation, then build up
to the parts of YAML that have no JSON analogue at all — anchors, tags, multi-document
streams — and the type-resolution rules that turn NO into false and 22:22 into
the integer 1342.
Start from JSON: flow style
Here is a JSON document. It is also a YAML document. Paste it into any conformant YAML parser and you get the identical structure back:
{"name": "blowhole", "version": 3, "tags": ["cs", "viz"], "stable": true, "notes": null}
YAML calls this flow style — collections written inline with {} and [] and
, separators, exactly like JSON. Flow style is YAML's "JSON compatibility mode." The
mapping to what you know is one-to-one:
JSON thinks
{} is an object, [] is an
array, keys are strings, values are typed.
YAML thinks
{} is a mapping, [] is a
sequence, keys are (usually) strings, values are typed. Same tree.
The vocabulary differs — YAML says mapping / sequence / scalar where JSON says object / array / value — but the data model is the same nested tree of key-value maps, ordered lists, and leaf scalars. If you only ever wrote YAML in flow style, you'd essentially be writing JSON with optional quotes. Which raises the obvious question: why does anyone put up with the whitespace-sensitive version?
Block style: the same tree, minus the punctuation
The reason YAML exists is block style — the indentation-based syntax that lets you drop almost every bracket, brace, comma, and quote. Here is the exact same document, twice:
JSON / YAML flow style
{
"name": "blowhole",
"version": 3,
"tags": ["cs", "viz"],
"stable": true,
"notes": null
}
YAML block style
name: blowhole
version: 3
tags:
- cs
- viz
stable: true
notes: null
Read off the transformation:
- The outer
{ }is gone. Top-level structure is implied by indentation. - Keys lose their quotes.
name:instead of"name":. - The
,between entries is gone — a newline is the separator. - Array elements become a
-(dash + space) per line instead of[ , ]. - Strings that look like plain words lose their quotes too.
blowhole, not"blowhole". 3,true, andnullare written identically — and, importantly, still parse to a number, a boolean, and null.
The visual diagram of what moved where:
Because flow style is legal inside block style, you can mix them freely. tags: [cs, viz]
on one line is perfectly fine YAML — it's a block mapping whose value happens to be a flow
sequence. This is why so much real-world YAML has a JSON-ish array hiding on the right-hand
side of a key.
Here's a live converter so you can watch the punctuation dissolve both ways. Paste JSON, read YAML; edit YAML, read JSON back.
Block mappings, block sequences, and the indentation rules
Two structural building blocks, both driven by indentation.
A block mapping is a set of key: value lines at the same indentation:
host: localhost
port: 5432
ssl: false
A block sequence is a set of - item lines at the same indentation:
- alice
- bob
- carol
Nesting is just deeper indentation. A value can itself be a mapping or a sequence:
server:
host: localhost
port: 5432
aliases:
- db-primary
- db-1
users:
- name: alice
admin: true
- name: bob
admin: false
That last block is the one JSON-fluent readers should stare at. users is a sequence of
two mappings. The - sits at the sequence's indentation; the keys of each mapping
(name, admin) line up with each other after the dash. The JSON is:
{"users": [{"name": "alice", "admin": true}, {"name": "bob", "admin": false}]}
The rules that make indentation unambiguous:
- Indent with spaces only. Tabs are forbidden for indentation — a literal tab character where the parser expects indentation is a hard error in conformant parsers. This is the single most common "why won't my YAML parse" cause. Configure your editor to insert spaces.
- The number of spaces doesn't matter, only that it's consistent within a block. Two spaces is the near-universal convention; pick it and never think about it again.
- A
-counts as indentation. In- name: alice, thenamekey is considered indented past the dash, so a followingadmin:must line up undername, not under-. - Keys are separated from values by a colon followed by a space:
port: 5432, notport:5432. The space is required in block context (the colon-space is the mapping indicator).
Comments
The thing JSON conspicuously lacks. A # begins a comment that runs to end of line,
anywhere outside a quoted scalar:
port: 5432 # the postgres default
# whole-line comment
There is no block-comment syntax; every commented line needs its own #. This single
feature is why so many projects tolerate everything else about YAML — you cannot annotate
a JSON config, and you can annotate a YAML one.
Scalars: three ways to write a leaf value
In JSON a string is a string: double quotes, backslash escapes, done. YAML gives you three scalar styles, and the differences are not cosmetic — they change what characters are legal and how escapes work.
1. Plain (unquoted)
name: blowhole
greeting: hello world
path: /usr/local/bin
No quotes at all. Cleanest to read, and the source of every type-resolution surprise
in the next section, because a plain scalar's type is guessed from its
content. No escape sequences are processed — a backslash is a literal backslash.
Certain characters are forbidden in plain scalars because they'd be ambiguous
(leading [ ] { } , # & * ! | > ' " % @ `, and :
or # in the middle).
2. Single-quoted
path: 'C:\Users\alice'
literal: 'he said "hi"'
apostrophe: 'it''s fine'
Everything between the quotes is literal — no backslash escapes at all.
A backslash is just a backslash, which makes single quotes ideal for Windows paths and
regexes. The one and only escape is a doubled '' to get a literal single
quote. This is closest to a "raw string."
3. Double-quoted
tab: "a\tb"
newline: "line1\nline2"
unicode: "☃ is a snowman"
quote: "he said \"hi\""
The JSON string, essentially. Backslash escapes work exactly as in JSON
(\n, \t, \", \\, \uXXXX),
plus a few YAML extras (\0, \x41, \U0001F600).
Use double quotes when you need real control characters inside the string.
When must you quote?
Quote a scalar when its plain form would either be illegal (it starts
with an indicator character, or contains : / #) or would
resolve to the wrong type (the string no, 1.10,
0777, 2024-01-01, an empty string, or a git SHA that's all
digits). When in doubt, quote. The rest of this article is a catalogue of the cases
where "in doubt" applies.
Type resolution: the heart of the gotchas
In JSON, a value's type is unambiguous from its syntax: quotes mean string, true/false
mean boolean, null means null, and bare digits mean number. There is exactly one way to
write each.
In YAML, a plain scalar has no syntactic type — the parser looks at the text and
guesses. port: 5432 is a number because 5432 matches the integer pattern. name: 5432
would also be a number, which is probably not what you wanted for an ID. The set of
patterns the parser tries is called the schema, and this is where YAML's two live
versions diverge violently.
YAML 1.2 core schema (the spec, 2009)
A small, sane set. Booleans are only true/false. Null is
null / ~ / empty. Ints are decimal, 0x hex,
0o octal. Floats are JSON-style plus .inf/.nan.
That's it.
YAML 1.1 (what your parser probably does)
A sprawling set inherited from 2005. Booleans include
yes/no/on/off/y/n in every capitalisation. Leading-zero numbers are
octal. Colon-separated digits are base-60. This is
the version PyYAML's default loader, libyaml, and countless others still implement.
The version trap
YAML 1.2 came out in 2009 and fixed most of these footguns. But most deployed parsers
still default to 1.1 semantics, and a bare document has no way to
opt into 1.2 unless it starts with a %YAML 1.2 directive — which nobody
writes. So the rules that actually govern your CI config are, in practice, the messy
1.1 ones. Assume 1.1 unless you've verified otherwise.
Here is the resolution order a 1.1-style parser applies to a plain scalar. First match wins:
Notice that string is the fallback, not the default. Every other pattern gets first refusal on your unquoted text. That inversion — "it's a string only if it fails to look like anything else" — is the root cause of every horror story below.
A field guide to the gotchas
Each of these is a real bug that has shipped to production somewhere. The fix for every single one is the same — quote the scalar — but you have to know the trap exists to know you need to.
The Norway problem
The famous one. A list of country codes:
countries:
- GB
- NO
- SE
- FR
Under YAML 1.1, NO is not the string "NO" — it's the boolean false. So Norway
silently vanishes from your data and becomes [..., false, ...]. The full YAML 1.1
boolean token set is:
y Y yes Yes YES n N no No NO
true True TRUE false False FALSE
on On ON off Off OFF
That means on, off, yes, no, and a bare y or n are all booleans too. A config
value like feature_x: on is true, not the string "on". Fix: - "NO" or
feature_x: "on".
Sexagesimal — base-60 integers
YAML 1.1 inherited a syntax for entering times and angles as base-60 numbers: digits separated by colons. So:
start: 22:22
22:22 matches the sexagesimal integer pattern and resolves to 22 × 60 + 22 = 1342 —
an integer, not a time string. A MAC-address-ish or HH:MM value walks straight into
this. YAML 1.2 removed sexagesimal entirely, but 1.1 parsers still do it. Fix: "22:22".
Leading zero → octal
zip: 07030
mask: 0777
A plain scalar of digits with a leading 0 is read as octal in 1.1. 0777 is
511 decimal; 07030 is either octal (if all digits are 0–7) or, because 8 isn't a
valid octal digit, falls back to string for something like 08000. So a US ZIP code, a
zero-padded ID, or a Unix file mode all mutate. Fix: quote it, or in 1.2 use the explicit
0o777 octal prefix.
Version strings and git SHAs
version: 1.10
sha: 8080808
1.10 is a float, and floats drop trailing zeros — so version: 1.10 round-trips to
1.1, turning your "version one point ten" into "version one point one." And a git short
SHA that happens to be all digits (8080808) parses as the integer 8080808; a SHA with
a leading zero and only 0–7 digits parses as octal. Fix: version: "1.10", sha: "8080808".
Empty values are null
An omitted value is null, not an empty string:
name: alice
comment:
active: true
comment here is null, the same as writing comment: null or comment: ~. If you
wanted an empty string you must write comment: "". This bites when a template renders a
key with no value and downstream code expects "".
The many faces of null
YAML spells null several ways, all equivalent: null, Null, ~, and nothing at all.
The ~ in particular is idiomatic YAML with no JSON counterpart:
a: null
b: ~
c:
d: Null
All four values are null. And an unquoted NULL in ALL CAPS is also null in 1.1 — but a
quoted "null" is the string. Quotes always defeat resolution.
The golden rule that dissolves all of the above
Quotes turn resolution off. A quoted scalar (single or double) is
always a string, full stop. "NO" is the string NO,
"22:22" is the string 22:22, "0777" is the four-character
string, "1.10" keeps its trailing zero. If a value is conceptually text —
an ID, a code, a version, a path, a SHA — quote it and none of the type-guessing rules
can touch it.
Multiline strings: literal and folded blocks
JSON has one way to embed a newline in a string: \n inside a double-quoted value. YAML
has that too, but its signature feature is block scalars — multi-line strings written
with real line breaks and no escaping. There are two flavours, and the difference is
entirely about what happens to your newlines.
Literal | — newlines are preserved
script: |
echo "building"
make all
echo "done"
The | says "keep every line break literally." The value is:
echo "building"
make all
echo "done"
with a trailing newline. This is the one you want for shell scripts, embedded config files, or anything where line structure matters. The indentation of the block (here, two spaces) is stripped; everything to the right of it is content.
Folded > — newlines become spaces
description: >
This is one long
paragraph that happens
to be wrapped for readability.
The > folds single line breaks into spaces, so the value is one line:
This is one long paragraph that happens to be wrapped for readability.
with a trailing newline. Use it for prose you want to soft-wrap in the source but store as a single line. (A blank line in a folded block is preserved as one newline — that's how you get paragraph breaks.)
Chomping: what happens to the trailing newline
Both | and > take a chomping indicator controlling the final newline(s):
Clip (default) — |
Exactly one trailing newline is kept, regardless of how many blank lines follow. This is the sensible default.
Strip — |-
No trailing newline at all. Use when you need the value to end exactly at the last character (e.g. a token, a single-line secret).
And keep — |+ — preserves every trailing blank line as newlines. The three side by
side, for a block whose content is foo followed by two blank lines:
Same content, three chomping modes
clip | → "foo\n" (one newline)
strip |- → "foo" (no newline)
keep |+ → "foo\n\n\n" (all trailing newlines kept)
The same three indicators work on folded blocks: >,
>-, >+. If you've ever had a Kubernetes secret fail
because of a stray trailing newline, |- is the fix.
Anchors, aliases, and merge keys: no JSON analogue
Here YAML leaves JSON behind entirely. JSON is a pure tree — every value is written out in full, and there is no way to say "the same value as over there." YAML has references.
An anchor &name labels a node; an alias *name refers back to it. The parser
substitutes the anchored node's value wherever the alias appears:
default: &db_defaults
adapter: postgres
host: localhost
pool: 5
development:
<<: *db_defaults
database: app_dev
production:
<<: *db_defaults
database: app_prod
host: db.internal
Two new pieces:
&db_defaultsanchors the mapping underdefault.*db_defaultsaliases it — inserts that same mapping.<<:is the merge key: it merges the aliased mapping's keys into the current mapping, with local keys winning. Soproductiongetsadapter,pool, anddatabase, plus its ownhost: db.internaloverriding the default.
Two caveats on references
First, the merge key << is not part of the YAML 1.2 core
spec — it was a 1.1 "language-independent type" that most parsers still
support, but not all, and 1.2 pointedly does not require it. Second, an alias is a
reference to the same node, not a deep copy; a serializer that emits the data
back out may or may not reconstruct the anchors, so round-tripping is not guaranteed.
The billion-laughs attack
References make YAML a small graph language, and graphs can be exponential. The classic denial-of-service payload:
a: &a ["lol","lol","lol","lol","lol","lol","lol","lol","lol"]
b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]
c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]
d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]
e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]
Each level multiplies the previous by nine. A handful of short lines expands to billions of nodes when a naive parser materialises the whole tree, exhausting memory — the "billion laughs" / YAML-bomb attack. This is one reason you never feed untrusted YAML to a parser that resolves aliases without limits, and why hardened loaders cap alias expansion.
Tags, documents, and streams
Explicit tags
If you don't trust implicit resolution, you can force a type with a tag. The !!
prefix names a built-in type from the YAML tag namespace:
port: !!str 5432 # the string "5432", not the number
count: !!int "5432" # the number 5432, from a quoted-looking scalar
flag: !!bool "true"
!!str, !!int, !!float, !!bool, !!null, !!map, !!seq are the core tags.
A single ! introduces an application-specific tag — !Circle, !include — that a
custom parser or a framework interprets (CloudFormation's !Ref, !GetAtt are exactly
this). This is powerful and exactly why untrusted YAML is dangerous: some loaders map tags
to arbitrary object construction (Python's yaml.load historically could instantiate
classes), which is remote code execution waiting to happen. Always use the safe loader
(yaml.safe_load, SafeConstructor, etc.) on input you didn't write.
Documents and the --- / ... markers
A single YAML stream can contain multiple documents, separated by ---. An optional
... marks the end of a document. This is the feature Kubernetes manifests lean on — one
file, many resources:
---
kind: Service
name: web
---
kind: Deployment
name: web
replicas: 3
...
A leading --- on its own also just means "here begins a document" and is common at the
top of a single-document file. JSON has no equivalent — a JSON file is exactly one value.
(The JSON-Lines / NDJSON convention of one JSON value per line is the closest analogue, and
it's a separate convention, not part of JSON itself.) Parsers expose this as
load_all / parse_all returning an iterator of documents.
Where real parsers disagree
Because the spec has two live versions and the ecosystem never fully migrated, "valid YAML" is fuzzier than "valid JSON." Concretely:
- Schema version. PyYAML, libyaml, and many others default to 1.1 resolution
(Norway, octal, sexagesimal). Go's
gopkg.in/yaml.v3, JavaScript'syaml, and others lean toward 1.2 behaviour. The same file can parse to different data in two languages. - The superset isn't perfect in practice. Even though 1.2 is designed as a strict
JSON superset, a 1.1-defaulting parser will mis-handle JSON edge cases:
{"a": 1e2}parses1e2as the string"1e2"under 1.1 (which requires1.0e+2), where JSON says the number100. And a literal tab inside JSON whitespace can trip stricter YAML parsers. So "every JSON file is valid YAML" is true for the language but not always for the parser in front of you. - Duplicate keys. JSON says keys "SHOULD" be unique; YAML says they "MUST" be, and conformant parsers error on duplicates. Portable JSON (unique keys) is fine; JSON that relies on last-key-wins is not portable YAML.
- Merge keys and tags. Support for
<<and for particular!tagsvaries. Don't assume a feature works everywhere just because your parser has it.
Practical guidance — the short version
- Quote every string that could be mistaken for something else — IDs,
versions, codes, country abbreviations, times, ZIPs, SHAs, and anything from
yes/no/on/off/y/n. - Prefer the 1.2 core schema where your parser lets you select it
(e.g. Python's
ruamel.yamlwith the 1.2 setting). - Use the safe loader on any YAML you didn't author. Never
yaml.loaduntrusted input. - Cap alias expansion or disable anchors when parsing untrusted data, to defuse YAML bombs.
- Run a linter (
yamllint) in CI to catch tabs, duplicate keys, and surprise types before they ship.
When to use YAML vs JSON
They're good at opposite jobs, and the split is clean.
Reach for YAML when…
- A human authors and reads the file: CI pipelines, Kubernetes manifests, Ansible playbooks, app config.
- You need comments to explain choices.
- You want multi-line strings (embedded scripts, prose) without escaping.
- Shared boilerplate benefits from anchors / merge keys.
Reach for JSON when…
- Machines produce and consume it: API payloads, RPC, logs, message queues.
- You need one unambiguous parse across every language, with no schema-version roulette.
- Speed and simplicity matter — JSON parsers are faster and far smaller.
- Untrusted input is involved and you want the smallest possible attack surface.
A common and healthy pattern: author in YAML, transmit in JSON. Tools read the human-friendly YAML, then serialise to JSON for the wire — you get comments and anchors at edit time and unambiguous, fast parsing at run time. Since every YAML document reduces to the JSON data model, that conversion is lossless for the data (you lose only the comments and the sharing that anchors expressed).
Key Takeaways
- YAML 1.2 is a superset of JSON — start from JSON flow style, then drop the braces, quotes, and commas to get block style.
- Indentation is spaces-only (never tabs); a colon-space makes a mapping, a
dash-space makes a sequence, and
#starts a comment. - Plain scalars are typed by guessing — string is the fallback, not the default — which is where every gotcha lives.
- YAML 1.1 (what most parsers still do) reads
NOas false,0777as octal,22:22as 1342, and empty as null. Quotes turn all of that off. |keeps newlines,>folds them to spaces;-/+chomping controls the trailing newline.- Anchors (
&), aliases (*), merge keys (<<), tags, and multi-document streams have no JSON analogue — and anchors enable the billion-laughs DoS. - Author in YAML, transmit in JSON: comments and reuse for humans, one unambiguous parse for machines.
Sources for the trickier facts in this article: the YAML 1.1 boolean type and integer type definitions, the YAML 1.2 specification, and John Millikin's "JSON is not a YAML subset".