Skip to content

Convert JSON to YAML with Python

[

Python Convert JSON to YAML

In Python, there are several ways to convert JSON data into YAML format. This tutorial will walk you through the step-by-step process of converting JSON to YAML using different methods.

Method 1: Using the pyyaml Library

The pyyaml library provides a simple and straightforward way to convert JSON to YAML. You can install it using pip by running the following command:

pip install pyyaml

Once installed, you can use the following code to convert JSON data to YAML:

import json
import yaml
# Load JSON data
with open('data.json') as file:
data = json.load(file)
# Convert JSON to YAML
yaml_data = yaml.dump(data)
# Save YAML data to a file
with open('data.yaml', 'w') as file:
file.write(yaml_data)

The above code reads the JSON data from a file called data.json, converts it to YAML format using the dump() function from the yaml module, and then saves the converted data to a file called data.yaml.

Method 2: Using the ruamel.yaml Library

Another popular library for converting JSON to YAML is ruamel.yaml. Unlike pyyaml, ruamel.yaml preserves the order of keys in dictionaries. You can install it using pip by running the following command:

pip install ruamel.yaml

Here’s an example of how to use ruamel.yaml to convert JSON to YAML:

import json
import ruamel.yaml
# Load JSON data
with open('data.json') as file:
data = json.load(file)
# Convert JSON to YAML
yaml_data = ruamel.yaml.round_trip_dump(data, indent=2)
# Save YAML data to a file
with open('data.yaml', 'w') as file:
file.write(yaml_data)

In this code, the JSON data is loaded from the data.json file, converted to YAML format using the round_trip_dump() function from ruamel.yaml, and then saved to a file called data.yaml.

Method 3: Using the json2yaml Command-Line Tool

If you prefer a command-line tool for converting JSON to YAML, you can use the json2yaml package. It allows you to convert JSON files directly from the command line without writing any code.

First, install json2yaml using pip:

pip install json2yaml

Once installed, you can use the following command to convert a JSON file to YAML:

json2yaml input.json output.yaml

Replace input.json with the path to your JSON file and output.yaml with the desired path for the YAML file.

Conclusion

In this tutorial, we explored three different methods for converting JSON to YAML in Python. You can choose the method that best suits your needs, whether it’s using the pyyaml or ruamel.yaml libraries, or utilizing the json2yaml command-line tool. Whichever method you choose, you now have the tools to effortlessly convert JSON data into YAML format. Happy coding!