JSON and YAML can describe the same data. They differ in who they are written for: JSON for machines, YAML for people editing by hand.
The same config in both
JSON
{
"service": "checkout",
"replicas": 3,
"debug": false,
"ports": [8080, 9090],
"env": {
"LOG_LEVEL": "info",
"REGION": "eu-west-1"
}
}
YAML
# Checkout service
service: checkout
replicas: 3
debug: false
ports:
- 8080
- 9090
env:
LOG_LEVEL: info
REGION: eu-west-1
Comparison
| JSON | YAML | |
|---|---|---|
| Structure | Braces and brackets | Indentation (spaces only) |
| Comments | Not allowed | # comment |
| Strings | Always double-quoted | Usually unquoted |
| Multi-line strings | Escaped \n | Block scalars | and > |
| Reuse | None | Anchors and aliases (&base, *base) |
| Multiple documents per file | No | Yes, separated by --- |
| Type inference | Explicit | Implicit (can surprise you) |
| Parser complexity | Tiny, fast, everywhere | Large; behaviour varies by version |
| Typical use | APIs, package.json, generated files | Kubernetes, GitHub Actions, Compose, CI |
Where YAML bites
Implicit typing. YAML guesses types from unquoted values. Depending on the parser's YAML version:
country: NO # false in YAML 1.1 parsers (the "Norway problem")
version: 1.10 # the number 1.1, not the string "1.10"
zip: 012345 # may become an octal or decimal number
time: 12:30 # sexagesimal 750 in some YAML 1.1 parsers
Quote anything that must stay a string: country: "NO", version: "1.10".
Indentation. A single misplaced space moves a key to a different parent, and tabs are not allowed at all. The file still parses; it just means something else.
Unsafe loading. Some YAML loaders can construct arbitrary objects (Python's yaml.load without a safe loader, for example). Always use the safe loader for untrusted input.
Where JSON bites
- No comments, so explaining a setting means a separate README or a
"_comment"key. - Trailing commas and single quotes are syntax errors.
- Noisy to hand-edit in big files: every string quoted, every level closed.
Which should you use?
- The tool decides first. Kubernetes accepts both, GitHub Actions only YAML, npm only JSON. Use what the ecosystem expects.
- Generated or machine-read files (API payloads, lockfiles, build output): JSON.
- Hand-edited config with comments: YAML, or JSONC if the tool supports it.
- Validation: both work with JSON Schema. Editors use it for YAML autocompletion too (see the JSON Schema guide).
Converting with yq
# YAML → JSON
yq -o=json '.' deployment.yaml > deployment.json
# JSON → YAML
yq -P '.' deployment.json > deployment.yaml
This is mikefarah's Go yq. Converting YAML to JSON drops comments, and anchors are expanded into copies.
Related comparisons
- JSON vs JSONL for logs and datasets.
- JSON vs TOON for prompts sent to LLMs.