YAML vs JSON: When to Use Each
Both serialize data as key-value pairs, but they serve different purposes. A practical comparison with gotchas.
YAML and JSON are the two most popular data serialization formats in modern development. JSON powers every REST API. YAML powers every CI/CD pipeline, Kubernetes manifest, and Docker Compose file. Choosing the right one matters.
Syntax comparison
# YAML — clean, readable
server:
port: 3000
host: localhost
features:
- auth
- logging
- rate_limit
{
"server": {
"port": 3000,
"host": "localhost"
},
"features": ["auth", "logging", "rate_limit"]
}
YAML drops quotes, commas, and braces. JSON requires strict punctuation but is unambiguous.
When to use YAML
- Configuration files — Docker Compose, Kubernetes, Ansible, GitHub Actions
- Human-authored data — content frontmatter, API specs (OpenAPI)
- When readability is the priority — less visual noise, comments allowed
YAML supports features JSON doesn't: comments (#), multi-line strings (| and >), anchors (&), aliases (*), and merge keys (<<).
When to use JSON
- API request/response bodies — universally parsed, no ambiguity
- Programmatic data —
JSON.parse()/JSON.stringify()in every language - When machine-generated — no reason for human-friendly syntax
- LLM token efficiency — JSON actually costs fewer tokens than equivalent YAML because it doesn't require indentation tokens
The YAML gotchas
YAML's flexibility creates footguns that JSON avoids:
1. The Norway problem:
country: NO # YAML parses this as boolean false (NO = false)
country: 'NO' # Quote it to get the string "NO"
2. Implicit type coercion:
version: 1.0 # float 1.0
version: 1.10 # float 1.1 (trailing zero stripped)
version: '1.10' # string "1.10" (what you probably meant)
3. Tabs are illegal — YAML uses spaces for indentation. A single tab character breaks the entire file.
4. Anchors and aliases can create circular references that break naive serializers.
Converting between formats
YAML to JSON is straightforward — most parsers handle it. JSON to YAML can produce unexpected results if your JSON contains null values or deeply nested structures that YAML represents differently.
# YAML to JSON
yq -o=json config.yaml > config.json
# JSON to YAML
jq '.' config.json > config.yaml
The YAML Toolkit validates, auto-fixes syntax errors, merges multiple YAML files with conflict resolution, and converts YAML to JSON, TOML, Properties, and
.env— all client-side.