• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Convert JSON to YAML in Python

Convert JSON to YAML in Python

Author: Aditya Raj
Last Updated: February 3, 2023

Different software uses different file formats for storing and transmitting data. Hence, we often need to convert data from one format to another. This article will discuss how we can convert JSON to YAML in python.

Table of Contents
  1. What is JSON Format?
  2. What is YAML Format?
  3. Convert JSON string to YAML string in Python
  4. Convert JSON file to the YAML format
  5. JSON to YAML Online 
  6. Conclusion

What is JSON Format?

JSON (JavaScript Object Notation) is a lightweight data interchange format. It is easy for humans to read and write and for machines to parse and generate. The JSON format is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999.

In JSON, attributes and their values are represented as key-value pairs just like a python dictionary. The keys and values are separated by a colon and enclosed in curly braces. Nested attributes are represented as nested key-value pairs. The data structure is easy to read and understand, making JSON a popular format for data exchange and storage.

A simple JSON file with nested attributes looks as follows.

{
  "employee": {
    "name": "John Doe",
    "age": 35,
    "job": {
      "title": "Software Engineer",
      "department": "IT",
      "years_of_experience": 10
    },
    "address": {
      "street": "123 Main St.",
      "city": "San Francisco",
      "state": "CA",
      "zip": 94102
    }
  }
}

In this example, the employee attribute has several nested attributes, such as name, age, job, and address. The job attribute has further nested attributes, including title, department, and years_of_experience.

What is YAML Format?

YAML (Yet Another Markup Language) is a human-readable data serialization language used to store and transmit data. It is commonly used for configuration files, data exchange between languages and platforms, and software development.

We can represent the JSON data shown in the previous example using YAML as shown below.

employee:
  name: John Doe
  age: 35
  job:
    title: Software Engineer
    department: IT
    years_of_experience: 10
  address:
    street: 123 Main St.
    city: San Francisco
    state: CA
    zip: 94102

The YAML syntax uses indentation to show the relationship between the attributes, making it easy to understand the structure of the data.

Convert JSON string to YAML string in Python

To convert a JSON string to a YAML string, we will first convert the json string to a python dictionary using the loads() method defined in the json module. The loads() method takes a json string as its input argument and returns a python dictionary after execution.

Once we get the dictionary, we can convert it to a YAML string using the dump() method defined in the yaml module. The dump() method takes the python dictionary as its input argument and returns the YAML string as shown in the following example.

import json
import yaml
json_string='{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}'
print("The JSON string is:")
print(json_string)
python_dict=json.loads(json_string)
ymal_string=yaml.dump(python_dict)
print("The YAML string is:")
print(ymal_string)

Output:

The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
The YAML string is:
address:
  city: Anytown
  state: CA
  street: 123 Main St
  zipcode: '12345'
age: 32
email: [email protected]
name:
  first: John
  last: Doe

You can also convert a JSON string to a YAML file. For this, you can use the dump() method defined in the yaml module as shown below.

import json
import yaml
json_string='{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}'
print("The JSON string is:")
print(json_string)
python_dict=json.loads(json_string)
file=open("person_data.yaml","w")
yaml.dump(python_dict,file)
file.close()
print("YAML file saved.")

Output:

The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
YAML file saved.

In this example, we first opened a YAML file in write mode. Then, we passed the file pointer to the dump() method as its second input argument. Hence, the dump() method saves the data into the files instead of returning a string.

After execution of the above code, the output file looks as follows.

YAML Output
YAML Output

Convert JSON file to the YAML format

To convert a JSON file to YAML, we will use the following steps.

  • First, we will open the JSON file in read mode using the open() function. The open() function takes the file name of the json file as its input argument and returns a file pointer.
  • Next, we will load the json file to a python dictionary using the load() method defined in the json module. The load() method takes the file pointer of the json file as its input argument and returns a python dictionary.
  •  Once we get the dictionary, we can convert it to a YAML string using the dump() method defined in the yaml module. The dump() method takes the python dictionary as its input argument and returns the YAML string.

You can observe this in the following example.

import json
import yaml
file=open("person_data.json","r")
python_dict=json.load(file)
yaml_string=yaml.dump(python_dict)
print("The YAML file is:")
print(yaml_string)

Output:

The YAML file is:
address:
  city: Anytown
  state: CA
  street: 123 Main St
  zipcode: '12345'
age: 32
email: [email protected]
name:
  first: John
  last: Doe

To convert a JSON file to a YAML file, you can use the dump() method as shown below.

import json
import yaml
file=open("person_data.json","r")
python_dict=json.load(file)
file1=open("person_data1.yaml","w")
yaml.dump(python_dict,file1)
file1.close()
print("YAML file saved.")

Output:

YAML Output
YAML Output

JSON to YAML Online 

To convert JSON to YAML online, you can use jsontoyaml.com.

Conclusion

In this article, we have discussed different ways to convert a JSON file or string to YAML in python. To learn more about python programming, you can read this article on how to convert a dictionary to json in Python. You might also like this article on working with JSON files in Python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us