Converting YAML to JSON in Python is straightforward with PyYAML. Here's everything you need — from basic conversion to handling edge cases like multiple documents and special YAML types.
Install PyYAML
pip install pyyaml
Basic YAML to JSON conversion
import yaml
import json
# From a YAML string
yaml_string = """
name: Alice
age: 28
active: true
tags:
- developer
- python
"""
data = yaml.safe_load(yaml_string)
json_output = json.dumps(data, indent=2)
print(json_output)
# {
# "name": "Alice",
# "age": 28,
# "active": true,
# "tags": ["developer", "python"]
# }
Convert a YAML file to JSON file
import yaml, json
def yaml_file_to_json(yaml_path, json_path=None):
with open(yaml_path, 'r', encoding='utf-8') as f:
data = yaml.safe_load(f)
json_str = json.dumps(data, indent=2)
if json_path:
with open(json_path, 'w', encoding='utf-8') as f:
f.write(json_str)
return json_str
# Convert config.yaml to config.json
yaml_file_to_json('config.yaml', 'config.json')
Command line conversion (one-liner)
# Convert yaml file to json
python3 -c "import sys,yaml,json; print(json.dumps(yaml.safe_load(sys.stdin), indent=2))" < input.yaml > output.json
# Or using pipx/scripts
cat config.yaml | python3 -c "
import sys, yaml, json
data = yaml.safe_load(sys.stdin)
print(json.dumps(data, indent=2))
"
Handle multi-document YAML files
import yaml, json
# YAML files with multiple documents (separated by ---)
yaml_multi = """
name: Alice
---
name: Bob
"""
# yaml.safe_load_all returns a generator
documents = list(yaml.safe_load_all(yaml_multi))
json_output = json.dumps(documents, indent=2)
# [{"name": "Alice"}, {"name": "Bob"}]
Handle YAML dates and special types
import yaml, json
from datetime import date, datetime
yaml_str = """
created: 2023-11-14
updated: 2023-11-14T22:13:20Z
"""
data = yaml.safe_load(yaml_str)
# data['created'] is a Python date object — not JSON serializable by default
# Fix: custom JSON encoder for dates
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (date, datetime)):
return obj.isoformat()
return super().default(obj)
json_output = json.dumps(data, cls=DateEncoder, indent=2)
# {"created": "2023-11-14", "updated": "2023-11-14T22:13:20"}
Convert Kubernetes YAML to JSON
import yaml, json
with open('deployment.yaml', 'r') as f:
k8s_manifest = yaml.safe_load(f)
# Pretty-print the JSON
print(json.dumps(k8s_manifest, indent=2))
# Or save it
with open('deployment.json', 'w') as f:
json.dump(k8s_manifest, f, indent=2)
Try it free — YAML to JSON Converter
Convert YAML to JSON instantly in your browser — no Python needed for quick conversions.