How to Convert Between YAML and JSON
Learn YAML syntax, JSON comparison, Kubernetes and Docker use cases, common YAML mistakes, and when to choose one format over the other for configuration files.
YAML and JSON serve the same fundamental purpose: representing structured data as text. But they prioritize different things. JSON prioritizes machine parsing and strict syntax. YAML prioritizes human readability and editing comfort. Both formats appear constantly in modern development workflows, and converting between them is a task developers perform daily.
This guide covers YAML syntax from the ground up, compares it with JSON, walks through real-world use cases, and highlights the mistakes that catch even experienced developers. For quick conversions, use our YAML to JSON Converter.
YAML Syntax Basics
YAML (YAML Ain’t Markup Language) uses indentation and line breaks instead of braces and brackets. Here is a simple YAML document:
name: Alice
age: 30
active: true
address:
street: 123 Main St
city: Portland
state: OR
hobbies:
- hiking
- photography
- cooking
The equivalent JSON:
{
"name": "Alice",
"age": 30,
"active": true,
"address": {
"street": "123 Main St",
"city": "Portland",
"state": "OR"
},
"hobbies": ["hiking", "photography", "cooking"]
}
Core YAML rules:
- Key-value pairs use
key: valuesyntax. The space after the colon is required. - Nesting is indicated by indentation. Consistent indentation per level is mandatory.
- Lists use
- itemsyntax, with the dash followed by a space. - Strings don’t require quotes unless they contain special characters.
- Comments start with
#and run to the end of the line. JSON has no comment syntax. - Multiple documents in one file are separated by
---.
YAML Data Types
YAML infers types from values, which is both convenient and dangerous.
| Value | YAML Type | JSON Equivalent |
|---|---|---|
hello | String | "hello" |
42 | Integer | 42 |
3.14 | Float | 3.14 |
true / false | Boolean | true / false |
null or ~ | Null | null |
2026-02-09 | Date | "2026-02-09" (string) |
The type coercion trap: YAML interprets bare values that look like booleans, numbers, or dates automatically. This creates real problems:
# These are NOT strings in YAML
country: NO # Boolean false (Norway's ISO code)
version: 1.0 # Float, not string "1.0"
zip: 01234 # Octal number 668, not string "01234"
on: true # Boolean, not the word "on"
The fix: Quote values that should remain strings:
country: "NO"
version: "1.0"
zip: "01234"
on: "true"
This is one of the most common sources of YAML bugs and a strong reason to convert to JSON when strict typing matters.
JSON vs YAML Comparison
| Feature | YAML | JSON |
|---|---|---|
| Readability | High (minimal syntax) | Moderate (braces, quotes) |
| Comments | Yes (#) | No |
| Data types | Auto-inferred | Explicit |
| Multiline strings | Yes (block scalars) | No (use \n) |
| File size | Smaller (no braces/quotes) | Larger |
| Parsing speed | Slower | Faster |
| Error-proneness | Higher (indentation issues) | Lower (strict syntax) |
| Spec complexity | Large (200+ pages) | Small (10 pages) |
| Anchors/aliases | Yes | No |
JSON is a subset of YAML. Every valid JSON document is also valid YAML (since YAML 1.2). The reverse isn’t true because YAML supports features like comments, anchors, and multiline strings that JSON lacks.
Kubernetes and Docker Use Cases
YAML became the dominant configuration format in DevOps largely because of Kubernetes and Docker Compose.
Kubernetes Manifests
Kubernetes resources are defined in YAML files:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-server
labels:
app: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
Converting this to JSON is useful when you need to submit it programmatically via kubectl with the --output=json flag, or when building manifests dynamically in code where JSON libraries are more reliable than YAML generators.
Docker Compose
Docker Compose files define multi-container applications:
version: "3.8"
services:
web:
image: nginx:latest
ports:
- "8080:80"
volumes:
- ./html:/usr/share/nginx/html
depends_on:
- api
api:
build: ./api
environment:
DATABASE_URL: postgres://db:5432/app
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
Developers often convert these to JSON when integrating with CI/CD pipelines that generate configuration programmatically or when validating structure with JSON Schema.
YAML Indentation Rules
Indentation errors account for the majority of YAML parsing failures. The rules are strict:
- Spaces only. Tabs aren’t allowed and will throw a parse error. Configure your editor to insert spaces when you press Tab.
- Consistent levels. If the first level uses 2 spaces, every level must use 2 spaces. Mixing 2 and 4 spaces at the same nesting level breaks parsing.
- Alignment matters. List items at the same level must have their dashes aligned. Object keys at the same level must be aligned.
Correct:
server:
host: localhost
port: 8080
ssl:
enabled: true
cert: /etc/ssl/cert.pem
Broken (mixed indentation):
server:
host: localhost
port: 8080 # Wrong: 4 spaces instead of 2
ssl:
enabled: true # Wrong: 3 spaces instead of 2
Common YAML Mistakes
Forgetting to Quote Special Strings
The string yes becomes boolean true. The string 3.0 becomes a float. Country codes, version numbers, and timestamps all get silently converted to wrong types.
Duplicate Keys
YAML allows duplicate keys, but the behavior is undefined. Most parsers silently use the last value, discarding earlier ones:
name: Alice
age: 30
name: Bob # Silently overwrites "Alice"
JSON parsers also handle duplicates inconsistently, but linters catch them more readily.
Multiline String Confusion
YAML offers multiple multiline string syntaxes, and picking the wrong one changes the output:
# Literal block (preserves newlines)
description: |
Line one
Line two
# Folded block (joins lines with spaces)
description: >
Line one
Line two
# Literal block, strip trailing newline
description: |-
Line one
Line two
The | preserves line breaks. The > folds them into spaces. The - suffix strips the trailing newline. Getting these mixed up produces subtly different output that can break downstream processing.
Anchors That Create Circular References
YAML anchors (&name) and aliases (*name) allow reuse:
defaults: &defaults
timeout: 30
retries: 3
production:
<<: *defaults
timeout: 60
But circular references (anchor A references alias B which references anchor A) crash parsers. JSON has no equivalent feature, so anchors are expanded during conversion.
When to Choose YAML vs JSON
Choose YAML when:
- Humans will read and edit the file regularly
- You need comments to document configuration
- The tool expects YAML (Kubernetes, Ansible, GitHub Actions, Docker Compose)
- Multiline strings are common (descriptions, scripts)
Choose JSON when:
- Machines generate and consume the data
- Strict typing matters (APIs, data interchange)
- Parsing speed is critical
- You want minimal ambiguity in data types
- The file is consumed by JavaScript/TypeScript code
Convert Between Formats
Our YAML to JSON Converter parses YAML with full spec compliance and outputs clean, formatted JSON. Paste your YAML configuration, Kubernetes manifest, or Docker Compose file and get the JSON equivalent immediately.
Frequently Asked Questions
Can I add comments to JSON files?
Standard JSON doesn’t support comments. This is by design: JSON creator Douglas Crockford removed comments to prevent them from being used as parsing directives. Some tools support JSONC (JSON with Comments) or JSON5, which allow // and /* */ style comments, but these are non-standard extensions. If you need comments in your configuration, YAML is the better choice.
Why does my YAML file fail to parse?
The three most common causes are tab characters (use spaces only), inconsistent indentation (every level must use the same number of spaces), and unquoted special values (strings like yes, no, on, off, or values that look like numbers). Run your YAML through a linter to pinpoint the exact line and column of the error.
Is YAML slower to parse than JSON?
Yes. YAML parsing is significantly slower because the specification is more complex. JSON has a simple grammar with about 10 production rules. YAML has over 200 pages of specification covering multiple data types, anchors, tags, and flow styles. For configuration files loaded once at startup, the difference is negligible. For high-throughput data processing with thousands of files, JSON is measurably faster.
Do Kubernetes manifests have to be YAML?
No. Kubernetes accepts both YAML and JSON for all API resources. You can use kubectl apply -f deployment.json the same way you would with a YAML file. YAML is conventional because it’s more readable for human-edited configuration, but programmatically generated manifests often use JSON because it’s easier to produce correctly from code.
What happens to YAML features that JSON doesn’t support?
When converting YAML to JSON, features like comments are stripped (JSON has no comment syntax), anchors and aliases are expanded into their full values, and multiline strings are converted to single strings with \n characters. Date values become strings since JSON has no native date type. The data content is preserved, but the YAML-specific formatting and metadata get lost.
Related Calculators
Related Articles
- Color Theory Basics for Web Design
Master color theory for web design including the color wheel, complementary palettes, WCAG contrast requirements, and color psychology to create effective interfaces.
- How to Minify CSS for Faster Websites
Learn what CSS minification does, why it speeds up your website, what it removes from your stylesheets, and best practices for minifying CSS in production.
- Cron Job Examples for Common Tasks (Copy-Paste Ready)
Practical cron job examples with clear explanations. Copy-paste ready crontab schedules for backups, reports, cleanup, monitoring, and automation tasks.
- Common JSON Syntax Errors and How to Fix Them
Fix JSON syntax errors fast with this developer guide. Learn the top 5 JSON parsing errors, before/after examples, and debugging techniques to validate JSON instantly.
Share this article
Have suggestions for this article?