How to Convert YAML to JSON in Python — 3 Methods With Examples
- Method 1: PyYAML — pip install pyyaml, then yaml.safe_load + json.dumps.
- Method 2: ruamel.yaml — preserves comments during round-trip conversion.
- Method 3: browser tool — no Python code at all, instant visual result.
- Use safe_load, not load — the latter has security risks with untrusted YAML.
Table of Contents
Converting YAML to JSON in Python takes four lines of code using PyYAML. Install the package, load the YAML file with yaml.safe_load(), and serialize the result with json.dumps(). Done. If you want to preserve comments through the conversion or need round-trip fidelity, ruamel.yaml is the better choice. And if you do not want to write code at all, the free browser converter handles single-file conversions in your browser with no setup.
This guide covers all three methods with copy-paste examples, explains when to use each, and highlights the one security mistake that catches Python developers off guard.
Method 1: PyYAML — The Standard Python Approach
PyYAML is the most widely used Python YAML library. Install it once:
pip install pyyaml
Convert a YAML file to JSON:
import yaml
import json
with open('input.yaml', 'r') as f:
data = yaml.safe_load(f)
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
One-liner from the command line:
python3 -c "import yaml,json; print(json.dumps(yaml.safe_load(open('input.yaml')), indent=2))"
Convert a YAML string (not a file):
import yaml, json yaml_string = """ server: host: localhost port: 8080 debug: true """ data = yaml.safe_load(yaml_string) json_output = json.dumps(data, indent=2) print(json_output)
Output:
{
"server": {
"host": "localhost",
"port": 8080,
"debug": true
}
}
Critical: Use safe_load, Not load — A Common Python YAML Mistake
yaml.load() has a known security vulnerability. If you pass untrusted YAML to yaml.load() without specifying a Loader, it can execute arbitrary Python code during parsing. PyYAML will show a deprecation warning and eventually raise an error if you use it without a Loader argument.
Never do this with untrusted input:
# Dangerous — do not use this with untrusted YAML
data = yaml.load(open('input.yaml'))
Always use safe_load instead:
# Safe — use this for all YAML files from external sources
data = yaml.safe_load(open('input.yaml'))
yaml.safe_load() only handles basic YAML types (strings, numbers, booleans, lists, dicts) and does not allow Python object instantiation. For config files, CI/CD configs, Kubernetes manifests, and similar structured data, safe_load handles everything you need and prevents code injection.
If you need to process YAML that uses Python-specific tags, use yaml.load(f, Loader=yaml.SafeLoader) as an explicit alternative.
Method 2: ruamel.yaml — Preserve Comments During Conversion
PyYAML strips comments during loading. If you need to preserve YAML comments in a round-trip workflow (YAML → JSON → YAML with comments intact), use ruamel.yaml:
pip install ruamel.yaml
from ruamel.yaml import YAML
import json
yaml_parser = YAML()
yaml_parser.preserve_quotes = True
with open('input.yaml', 'r') as f:
data = yaml_parser.load(f)
# Convert to standard Python dict for json.dumps
json_ready = dict(data)
print(json.dumps(json_ready, indent=2))
Note: comment preservation works for YAML-to-YAML round trips. When converting to JSON, comments are still dropped (JSON has no comment syntax). ruamel.yaml's value is in workflows where you load a commented YAML config, modify values, and write it back to YAML — keeping the original comments in place.
For pure YAML-to-JSON conversion without round-trip requirements, PyYAML is simpler and faster.
Batch Convert Multiple YAML Files to JSON with Python
Convert an entire directory of YAML files to JSON:
import yaml, json, os, pathlib
input_dir = pathlib.Path('configs/')
output_dir = pathlib.Path('json-configs/')
output_dir.mkdir(exist_ok=True)
for yaml_file in input_dir.glob('*.yaml'):
with open(yaml_file) as f:
data = yaml.safe_load(f)
output_file = output_dir / yaml_file.with_suffix('.json').name
with open(output_file, 'w') as f:
json.dump(data, f, indent=2)
print(f'Converted: {yaml_file.name} -> {output_file.name}')
This is the main reason to write Python code for YAML-to-JSON conversion rather than using a browser tool — batch processing and automation. For a single file, the browser tool is faster than setting up a script.
Method 3: Skip the Code — Browser Tool for Instant Single-File Conversion
If you need to convert one YAML file and do not want to write any Python code, the browser converter is faster. Open the YAML to JSON tool, paste your YAML, click Convert. Done in under 10 seconds.
Use the browser tool when:
- You are debugging a YAML config and just need to see the JSON structure
- You are on a machine without Python installed
- You want a visual side-by-side view of the YAML and resulting JSON
- You only need to convert one file and will not repeat this task
Use Python when:
- You need to convert 10+ files at once
- The conversion is part of a build pipeline or CI/CD job
- You need to transform the data structure during conversion
- You need to validate the output against a schema
Need a Quick Conversion? Skip the Code.
Paste your YAML into the free browser converter — no Python install, no pip, no terminal. Instant JSON output.
Open Free YAML to JSON ConverterFrequently Asked Questions
How do I convert a YAML file to JSON in Python?
Install PyYAML with pip install pyyaml. Then: import yaml, json; data = yaml.safe_load(open("input.yaml")); print(json.dumps(data, indent=2)). Use safe_load, not load, for security.
What Python library should I use for YAML to JSON conversion?
PyYAML is the standard choice — it is widely used, well-maintained, and handles all common YAML structures. For workflows that require comment preservation during round-trips, ruamel.yaml is the better option.
Why should I use yaml.safe_load instead of yaml.load in Python?
yaml.load() can execute arbitrary Python code when parsing YAML containing Python-specific tags. This is a security risk with untrusted input. yaml.safe_load() only handles standard YAML types (dicts, lists, strings, numbers, booleans) and prevents code execution.
Can I convert a YAML string (not a file) to JSON in Python?
Yes. Pass the string directly to yaml.safe_load(): data = yaml.safe_load(my_yaml_string). Then serialize with json.dumps(data, indent=2). The function accepts both file objects and strings.

