How to Convert JSON to YAML in Python?

How to Convert JSON to YAML in Python?

How to Convert JSON to YAML in Python?

Install PyYAML Python library if it is not installed on your system.

pip install PyYAML

To check if the PyYAML Python library is installed or not on your system use the pip command along with the grep command.

pip list PyYAML | grep PyYAML  

Convert JSON to YAML in Python

Here is a simple Python program that converts JSON to YAML.

import json
import yaml

# Your JSON data
json_data = '{"key1": "value1", "key2": {"key3": "value3", "key4": "value4"}}'

# Parse JSON
parsed_data = json.loads(json_data)

# Convert to YAML
yaml_data = yaml.dump(parsed_data, default_flow_style=False)

# Print or save the YAML data as needed
print(yaml_data)

Output:

key1: value1
key2:
  key3: value3
  key4: value4

Explanation:

  • You have to import modules json and yaml.
  • Initialize any sample JSON data as a string that you want to convert into YAML format.
  • Parse the JSON file using json.load() function. It returns a Python dictionary.
  • Convert parsed data into YAML format using yaml.dump() function.

Here, argument default_flow_style is set to False to get human readable YAML format in yaml.dump() function.

If you set the argument default_flow_style to True, it gives us output YAML in a single line as below.

{key1: value1, key2: {key3: value3, key4: value4}}

The default value of the argument default_flow_style is False.

Python Code to Convert JSON file to YAML file

Instead of passing JSON string, you can also pass JSON file as input and convert it into a YAML file. Use Python file read/write operations.

import json
import yaml

# read json data from the file
with open('sample.json', 'r') as fd:
    json_data = fd.read()

# Parse JSON
parsed_data = json.loads(json_data)

# Convert to YAML
yaml_data = yaml.dump(parsed_data, default_flow_style=False)

# Write yaml data to the file
with open('output.yaml', 'w') as fd:
  fd.write(yaml_data)

Note:

Don’t forget to handle exceptions. If you implement this functionality in your project, invalid JSON data can also be passed. In this case, your program will throw an error for not passing valid JSON.

Usage:

There are many use cases where you need to convert JSON to YAML or vice-versa.

To give an instance, I am working on REST APIs and open APIs. Many times I have to convert openapi.json to openapi.yaml for documentation and API specification requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *