JSON vs YAML
JSON vs YAML — The Bottom Line
Use JSON for APIs, data interchange, and machine-generated data. Use YAML for config files written and maintained by humans. YAML is a superset of JSON — every JSON document is valid YAML, but not vice versa.
Side-by-Side Example
JSON (168 chars)
json
{
"server": {
"host": "localhost",
"port": 8080,
"debug": true
},
"database": {
"url": "postgresql://localhost/mydb",
"maxConnections": 10
},
"features": ["auth", "logging", "metrics"]
}YAML (115 chars)
yaml
server:
host: localhost
port: 8080
debug: true
database:
url: postgresql://localhost/mydb
maxConnections: 10
features:
- auth
- logging
- metricsDetailed Comparison
| Feature | JSON | YAML |
|---|---|---|
| Syntax | Braces, quotes, commas | Indentation, colons |
| Comments | Not supported | # line comments |
| Multiline strings | Escape \n | | literal, > folded blocks |
| Data types | 6 types | Many (dates, binary, etc.) |
| Anchors / aliases | No | Yes — &anchor and *alias |
| Human readability | Moderate | High — less punctuation |
| Machine parsing | Faster | Slower (complex spec) |
| Strictness | Strict spec | Spec has edge cases |
| Browser native | JSON.parse() | Needs library (js-yaml) |
| File size | Larger (quotes) | Smaller (no quotes needed) |
| Schema support | JSON Schema | Limited native support |
| Common use | REST APIs, config | Kubernetes, Docker, CI/CD |
When to Use JSON
- REST APIs — standard data interchange format, supported natively in every language
- Machine-generated data — serializing objects, databases, caches
- Browser environments — native JSON.parse() / JSON.stringify()
- Strict validation — JSON Schema is mature and well-tooled
- Simple configs — package.json, tsconfig.json, composer.json
When to Use YAML
- Kubernetes manifests — deployment.yaml, service.yaml, ingress.yaml
- CI/CD pipelines — GitHub Actions, GitLab CI, CircleCI
- Docker Compose — docker-compose.yml
- Ansible playbooks — infrastructure as code
- Application configs — Spring application.yml, Rails database.yml
- Docs with frontmatter — Hugo, Jekyll static sites
YAML Gotchas
yaml
# Booleans in YAML 1.1 (old parsers):
yes: true # "yes" is a boolean!
no: false # "no" is a boolean!
on: true # "on" is a boolean!
# Octal numbers:
mode: 0755 # parsed as 493 (octal), not 755!
# Norway problem:
country: NO # NO is a boolean "false" in YAML 1.1
# Fix: quote everything that looks ambiguous
mode: "0755"
country: "NO"