How to Convert YAML to JSON Using Python

Dec 28, 2023

1 min read

Published in

Understanding YAML and JSON

YAML (YAML Ain’t Markup Language) and JSON (JavaScript Object Notation) are both text-based formats used for configuration files, data exchange, and more. YAML is often preferred for its clean and concise syntax, while JSON is widely used in web development and APIs.

Prerequisites

Before we dive into the code, ensure you have the PyYAML library installed. You can install it using:

1
pip install pyyaml

Python Code to Convert YAML to JSON

Let’s create a simple Python script to demonstrate the conversion process:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import yaml
import json

def yaml_to_json(yaml_string):
    try:
        # Load YAML
        data = yaml. safe_load(yaml_string)
        
        # Convert to JSON
        json_data = json. dumps(data,  indent=2)
        
        return json_data
    except Exception as e:
        return f"Error: {e}"

# Example usage
yaml_string = """
name: John Doe
age: 30
city: New York
"""

json_data = yaml_to_json(yaml_string)
print(json_data)

Code Explanation

  1. Importing Libraries: We import the yaml and json libraries, which provide functions for working with YAML and JSON, respectively.

  2. yaml_to_json Function: This function takes a YAML string as input, uses yaml. safe_load to parse it into a Python data structure, and then converts it to a JSON-formatted string using json. dumps.

  3. Example Usage: We provide a simple YAML string as an example and call the yaml_to_json function to demonstrate the conversion.

Running the Script

Save the script to a file (e. g. , yaml_to_json_converter. py) and run it using:

1
python yaml_to_json_converter. py

You should see the converted JSON output on the console.

Sharing is caring!