JSON vs YAML for configuration: syntax, pitfalls, and how to choose
Where YAML buys you ergonomics, where it quietly coerces your data, why JSON stays the machine boundary, and a practical decision rule for config files.
问题
Where YAML buys you ergonomics, where it quietly coerces your data, why JSON stays the machine boundary, and a practical decision rule for config files.
Pasos
-
1. The ergonomic difference
YAML trades JSON's punctuation for indentation: no braces or quotes for most values, comments (#) are first-class, anchors (&base) and aliases (*ref) deduplicate repeated blocks, and multi-line strings are native (| and >). JSON has none of these — but what JSON lacks in comfort it returns in predictability: the grammar fits on a business card, every parser agrees on it, and diffs are purely structural.
-
2. The coercion pitfalls (the Norway problem)
YAML 1.1 interprets unquoted scalars against a type table, and the surprises are legendary: no becomes false (the Norway problem — country code NO silently turning into a boolean), version 1.10 becomes the number 1.1, on/off/yes/true/false are all booleans, and leading zeros can make values octal. YAML 1.2 fixed the worst of it (no is now the string no in core schema), but parsers are inconsistent about which version they implement — which is exactly why quoting version strings, country codes, and anything starting with 0 is mandatory discipline in real YAML files.
-
3. Where each one wins
JSON wins at machine boundaries: API payloads, log events, IPC, anything two independent programs must parse identically — its spec is unambiguous and its parsers are the most-tested code in the ecosystem. YAML wins where humans maintain the file: Kubernetes manifests, CI pipelines (GitHub Actions, GitLab CI), docker-compose — places where comments, multi-line strings, and anchors reduce real maintenance cost. Note the pattern: the industry converged on 'YAML at the human edge, JSON underneath' — Helm charts are YAML templates rendering JSON objects, and most YAML tools parse to the same data model JSON uses.
-
4. The migration checklist
When converting between the two (in either direction), verify four things: quote anything that looks numeric or boolean; expand or deliberately preserve anchors and aliases (JSON cannot represent them); check for duplicate keys (legal in lax YAML parsers, invalid in JSON, silently last-wins in others); and diff the parsed data models, not the text — the files can look right while the values have changed type. A formatter that validates JSON before conversion catches syntax errors at the first step instead of after deployment.
Resultado esperado
You can identify where YAML’s silent coercions (like the Norway problem) will corrupt your config, justify JSON as the machine-to-machine boundary, and apply the migration checklist before switching formats.