w3resource

Step-by-Step Guide to converting JSON to YAML in Python


Converting JSON to YAML

JSON (JavaScript Object Notation) and YAML (YAML Ain’t Markup Language) are popular formats for representing structured data. JSON is widely used in web applications and APIs, while YAML is preferred in configuration files due to its readability. Converting JSON to YAML is often necessary when transitioning between systems or using YAML for configurations.


Syntax of JSON and YAML

JSON Example:

{
    "name": "Macdara Herleif",
    "age": 30,
    "skills": ["Python", "JavaScript", "SQL"],
    "isEmployed": true
}

Equivalent YAML:

name: Macdara Herleif
age: 30
skills:
  - Python
  - JavaScript
  - SQL
isEmployed: true

Key differences:

  • YAML uses indentation instead of brackets and commas.
  • Keys and values are separated by a colon followed by a space.
  • Lists are represented using a dash (-) followed by a space.

Example: Python Code to Convert JSON to YAML

Python Code:

# Import json and yaml modules
import json
import yaml

# Define a JSON string
json_data = '''
{
    "name": "Macdara Herleif",
    "age": 30,
    "skills": ["Python", "JavaScript", "SQL"],
    "isEmployed": true
}
'''

# Parse the JSON string into a Python dictionary
data = json.loads(json_data)  # Convert JSON string to Python object

# Convert the Python dictionary to a YAML string
yaml_data = yaml.dump(data, default_flow_style=False)  # Pretty-print YAML

# Print the YAML string
print("YAML Output:\n", yaml_data)

Explanation:

    1. Importing Modules:

    • json module for parsing JSON data.
    • yaml module for converting Python objects to YAML format.

    2. Defining a JSON String:

    • A multi-line string represents the JSON data to be converted.

    3. Parsing JSON:

    • json.loads() converts the JSON string into a Python dictionary.

    4. Converting to YAML:

    • yaml.dump() takes the Python dictionary and converts it to a YAML string.
    • default_flow_style=False ensures that the output is in a human-readable format with proper indentation.

    5. Printing YAML Output:

    • The resulting YAML string is printed.

Output:

YAML Output:
 age: 30
isEmployed: true
name: Macdara Herleif
skills:
- Python
- JavaScript
- SQL

Additional Notes

    1. Installing PyYAML:

    • If the yaml module is not installed, use the following command to install PyYAML:
    • pip install pyyaml
      

    2. Saving YAML to a File:

    with open("output.yaml", "w") as file:
        yaml.dump(data, file, default_flow_style=False)
    

    3. Online Tools for JSON to YAML Conversion:

    • Tools like json2yaml or Online YAML Converter provide instant online conversion.

Practical Guides to JSON Snippets and Examples.



Follow us on Facebook and Twitter for latest update.