YAML and JSON are the two most commonly used data serialization formats in modern software development. YAML is known for its readability, while JSON is famous for its universality and strict syntax. This guide provides an in-depth look at the differences, conversion principles, and best practices.
Table of Contents
- Key Takeaways
- YAML vs JSON Comparison
- YAML Syntax Explained
- JSON Syntax Explained
- Conversion Principles
- Code Examples
- Common Use Cases
- Best Practices
- Frequently Asked Questions
- Conclusion
Key Takeaways
- YAML is a superset of JSON: All valid JSON is valid YAML
- Readability difference: YAML is more human-readable, JSON is easier for machines to parse
- Comment support: YAML supports comments, JSON does not
- Data types: Both support the same basic data types
- Use cases: YAML for config files, JSON for API data exchange
Need to quickly convert between YAML and JSON? Try our free online tools:
YAML vs JSON Comparison
| Feature | YAML | JSON |
|---|---|---|
| Readability | High (indentation) | Medium (brackets) |
| Comments | Supported (#) | Not supported |
| Data types | String, number, boolean, null, array, object | Same |
| File extension | .yaml, .yml | .json |
| Quotes | Optional in most cases | Required for strings |
| Multi-document | Supported (---) | Not supported |
| Anchors & aliases | Supported | Not supported |
| Parse speed | Slower | Faster |
| Common uses | Config files, CI/CD | APIs, data storage |
YAML Syntax Explained
Basic Structure
# This is a comment
name: John Doe
age: 30
active: true
email: null
# Nested object
address:
city: New York
country: USA
zipcode: "10001"
# Array
hobbies:
- reading
- coding
- gaming
# Inline array
skills: [JavaScript, Python, Go]
# Inline object
metadata: {created: 2024-01-01, updated: 2024-06-01}
Multi-line Strings
# Preserve line breaks (|)
description: |
This is a long description
that spans multiple lines.
Each line break is preserved.
# Fold line breaks (>)
summary: >
This is a long summary
that will be folded into
a single line.
Anchors and Aliases
# Define anchor
defaults: &defaults
adapter: postgres
host: localhost
port: 5432
# Use alias
development:
<<: *defaults
database: dev_db
production:
<<: *defaults
database: prod_db
host: prod.example.com
JSON Syntax Explained
Basic Structure
{
"name": "John Doe",
"age": 30,
"active": true,
"email": null,
"address": {
"city": "New York",
"country": "USA",
"zipcode": "10001"
},
"hobbies": ["reading", "coding", "gaming"]
}
Conversion Principles
YAML to JSON
- Parse YAML: Convert YAML text to in-memory data structure
- Handle special syntax: Expand anchors/aliases, process multi-line strings
- Serialize to JSON: Convert data structure to JSON string
- Remove comments: Comments are lost in conversion
JSON to YAML
- Parse JSON: Convert JSON text to data structure
- Formatting options: Indentation, inline format, quote strategy
- Serialize to YAML: Output according to YAML syntax rules
Code Examples
JavaScript/Node.js
const yaml = require('js-yaml');
// YAML to JSON
const yamlString = `
name: John Doe
age: 30
hobbies:
- reading
- coding
`;
const jsonObject = yaml.load(yamlString);
const jsonString = JSON.stringify(jsonObject, null, 2);
// JSON to YAML
const jsonData = {
name: "Jane Doe",
age: 25,
skills: ["Python", "JavaScript"]
};
const yamlOutput = yaml.dump(jsonData, { indent: 2 });
Python
import yaml
import json
# YAML to JSON
yaml_string = """
name: John Doe
age: 30
hobbies:
- reading
- coding
"""
data = yaml.safe_load(yaml_string)
json_string = json.dumps(data, indent=2)
# JSON to YAML
json_data = {"name": "Jane Doe", "age": 25}
yaml_output = yaml.dump(json_data, default_flow_style=False)
Common Use Cases
Kubernetes Configuration (YAML)
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
template:
spec:
containers:
- name: my-app
image: my-app:1.0.0
API Response (JSON)
{
"status": "success",
"data": {
"users": [
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"}
]
}
}
Best Practices
Choose the Right Format
| Scenario | Recommended | Reason |
|---|---|---|
| Config files | YAML | Readable, supports comments |
| API data | JSON | Universal, fast parsing |
| CI/CD configs | YAML | Industry standard |
| Frontend configs | JSON | Native support |
Conversion Considerations
- Comments lost: YAML to JSON loses comments
- Data types: Watch for YAML implicit type conversion
- Special characters: Strings with special chars need quotes
- Precision: Large numbers may lose precision
Frequently Asked Questions
When do YAML strings need quotes?
Quotes needed when:
- Contains special characters (
:,#,{,}, etc.) - Starts with special characters
- Looks like other data types (
yes,no,true) - Contains leading/trailing spaces
How to add comments in JSON?
JSON standard doesn't support comments. Alternatives:
- Use YAML format
- Use JSON5 (non-standard)
- Use special keys like
"_comment"
What happens to YAML anchors when converted to JSON?
Anchors and aliases are expanded into complete data copies.
Conclusion
YAML and JSON each have their advantages. Choosing the right format depends on your specific use case. Understanding the differences and conversion principles helps you handle config files and data exchange more efficiently.
Quick Summary:
- YAML for config files: readable, supports comments
- JSON for API data: universal, fast parsing
- YAML is a superset of JSON, conversion is straightforward
- Watch for data type and comment loss during conversion
Need to quickly convert between YAML and JSON? Try our free online tools: