How to Convert JSON to YAML in Python [Complete Guide]

To convert JSON to YAML in Python, install the PyYAML library (pip install pyyaml), load JSON with json.load(), then dump to YAML with yaml.dump(). Python doesn't support YAML natively like it does JSON, so PyYAML is required. Not sure which format to use? Check our YAML vs JSON comparison. This guide covers Python YAML vs JSON handling, and the conversion takes just a few lines of code.

Prerequisites

Before you start, make sure you have:

  • Python 3.x installed (check with python --version)
  • pip package manager (comes with Python)
  • A terminal or command prompt
Note: This guide uses Python 3. Python 2 is no longer supported, and PyYAML works best with Python 3.6+.

Install PyYAML

Python doesn't have built-in YAML support (unlike JSON, which is in the standard library). You need to install the PyYAML library. If you prefer using the command line instead, check out our CLI and yq guide.

# Install PyYAML
pip install pyyaml

# Or with pip3 on some systems
pip3 install pyyaml

# Verify installation
python -c "import yaml; print(yaml.__version__)"

PyYAML supports YAML 1.1 and is the most popular YAML library for Python. For YAML 1.2 support, consider ruamel.yaml instead. Need to do this in another language? See our JavaScript, Java, or Go guides.

Convert JSON to YAML in Python

Here's how to convert a JSON file to YAML in Python:

Step 1: Read JSON File

import json
import yaml

# Read JSON file
with open('data.json', 'r') as f:
    data = json.load(f)

Step 2: Convert to YAML

# Convert to YAML string
yaml_output = yaml.dump(data, default_flow_style=False)
print(yaml_output)

Step 3: Save to YAML File

# Save to YAML file
with open('data.yaml', 'w') as f:
    yaml.dump(data, f, default_flow_style=False)

Complete Example

import json
import yaml

def json_to_yaml(json_file, yaml_file):
    """Convert a JSON file to YAML format."""
    # Read JSON
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # Write YAML
    with open(yaml_file, 'w', encoding='utf-8') as f:
        yaml.dump(data, f, 
                  default_flow_style=False,
                  allow_unicode=True,
                  sort_keys=False)
    
    print(f"Converted {json_file} to {yaml_file}")

# Usage
json_to_yaml('config.json', 'config.yaml')
Tip: Use default_flow_style=False for block-style YAML (more readable) instead of inline flow style. Learn more about YAML vs JSON for configuration files.

Convert YAML to JSON in Python

Converting YAML back to JSON is equally simple:

import json
import yaml

def yaml_to_json(yaml_file, json_file):
    """Convert a YAML file to JSON format."""
    # Read YAML (use safe_load for security!)
    with open(yaml_file, 'r', encoding='utf-8') as f:
        data = yaml.safe_load(f)
    
    # Write JSON
    with open(json_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    
    print(f"Converted {yaml_file} to {json_file}")

# Usage
yaml_to_json('config.yaml', 'config.json')
Security warning: Always use yaml.safe_load() instead of yaml.load() when loading untrusted YAML files. The latter can execute arbitrary Python code! For quick conversions without code, try our online JSON to YAML converter.

Convert JSON String to YAML

For in-memory conversion without files:

import json
import yaml

def json_string_to_yaml(json_string):
    """Convert a JSON string to YAML string."""
    # Parse JSON string
    data = json.loads(json_string)
    
    # Convert to YAML
    yaml_string = yaml.dump(data, default_flow_style=False)
    return yaml_string

# Example usage
json_str = '{"name": "John", "age": 30, "skills": ["Python", "YAML"]}'
yaml_str = json_string_to_yaml(json_str)
print(yaml_str)

Output:

age: 30
name: John
skills:
- Python
- YAML

Handling Complex Data Types

Dates and Datetimes

JSON doesn't have a native date type, but YAML does:

from datetime import datetime
import yaml

data = {
    "created": datetime.now(),
    "expires": datetime(2025, 12, 31)
}

# yaml.dump() handles datetime objects automatically
yaml_output = yaml.dump(data, default_flow_style=False)
print(yaml_output)
# Output:
# created: 2025-12-17 10:30:00.123456
# expires: 2025-12-31 00:00:00

Multi-line Strings

import yaml

data = {
    "description": """This is a long description
that spans multiple lines.
It preserves line breaks."""
}

yaml_output = yaml.dump(data, default_flow_style=False)
print(yaml_output)
# Output uses literal block scalar (|)

Nested Objects

import json
import yaml

complex_data = {
    "server": {
        "host": "localhost",
        "port": 8080,
        "database": {
            "name": "mydb",
            "credentials": {
                "user": "admin",
                "password": "secret"
            }
        }
    }
}

yaml_output = yaml.dump(complex_data, default_flow_style=False)
print(yaml_output)

Common Errors and Solutions

Error Cause Solution
ModuleNotFoundError: No module named 'yaml' PyYAML not installed pip install pyyaml
yaml.YAMLError Invalid YAML syntax Check indentation, use a YAML validator
UnicodeDecodeError File encoding mismatch Add encoding='utf-8' to open()
json.JSONDecodeError Invalid JSON syntax Check for trailing commas, use double quotes
Keys sorted unexpectedly Default sorting behavior Use sort_keys=False in yaml.dump()

Handle Errors Gracefully

import json
import yaml

def safe_json_to_yaml(json_file, yaml_file):
    """Convert JSON to YAML with error handling."""
    try:
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        with open(yaml_file, 'w', encoding='utf-8') as f:
            yaml.dump(data, f, default_flow_style=False)
        
        return True
    except FileNotFoundError:
        print(f"Error: File '{json_file}' not found")
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON - {e}")
    except yaml.YAMLError as e:
        print(f"Error: YAML conversion failed - {e}")
    except Exception as e:
        print(f"Error: {e}")
    
    return False

Frequently Asked Questions

Is YAML built into Python?

No, Python doesn't include YAML support natively. You need to install a third-party library like PyYAML (pip install pyyaml). Unlike JSON, which has a built-in json module, YAML requires external packages for parsing and generation.

Is YAML written in Python?

YAML is a data format specification, not written in any specific language. However, PyYAML, the most popular Python YAML library, is written in Python with optional C extensions (libyaml) for better performance.

How to convert JSON to YAML in Python?

Install PyYAML (pip install pyyaml), load JSON data using json.load() or json.loads(), then convert to YAML using yaml.dump(). Use default_flow_style=False for readable output.

What is the difference between yaml.load() and yaml.safe_load()?

yaml.safe_load() only loads basic YAML tags and is secure against arbitrary code execution. yaml.load() can execute Python code, making it a security risk. Always use safe_load() for untrusted input.

Need to convert JSON to YAML quickly?

Use our free online converter—no installation required.

Open Converter Tool →