JSON (JavaScript Object Notation) is a file that is mainly used to store and transfer data mostly between a server and a web application. It is popularly used for representing structured data. In this article, we will discuss how to handle JSON data using Python. Python provides a module called json which comes with Python's standard built-in utility.
Note: In Python, JSON data is usually represented as a string.
Importing Module
To use any module in Python it is always needed to import that module. We can import json module by using the import statement.
Example: Importing JSON module
Python3
# importing json module
import json
Parsing JSON - Converting from JSON to Python
The load() and loads() functions of the json module makes it easier to parse JSON object.
Parsing JSON String
The loads() method is used to parse JSON strings in Python and the result will be a Python dictionary.
Syntax:
json.loads(json_string)
Example: Converting JSON to a dictionary
Python3
# Python program to convert JSON to Dict
import json
# JSON string
employee ='{"name": "Nitin", "department":"Finance",\
"company":"GFG"}'
# Convert string to Python dict
employee_dict = json.loads(employee)
print("Data after conversion")
print(employee_dict)
print(employee_dict['department'])
print("\nType of data")
print(type(employee_dict))
OutputData after conversion
{'name': 'Nitin', 'department': 'Finance', 'company': 'GFG'}
Finance
Type of data
<class 'dict'>
Note: For more information, refer to Parse Data From JSON into Python
Reading JSON file
load() method can read a file that contains a JSON object. Suppose you have a file named student.json that contains student data and we want to read that file.
Syntax:
json.load(file_object)
Example: Reading JSON file using Python
Let's suppose the file looks like this.
Python3
# Python program to read
# json file
import json
# Opening JSON file
f = open('data.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data:
print(i)
# Closing file
f.close()
Output:
Note:
- JSON data is converted to a List of dictionaries in Python
- In the above example, we have used to open() and close() function for opening and closing JSON file. If you are not familiar with file handling in Python, please refer to File Handling in Python.
- For more information about readon JSON file, refer to Read JSON file using Python
Convert from Python to JSON
dump() and dumps() method of json module can be used to convert from Python object to JSON.
The following types of Python objects can be converted into JSON strings:
- dict
- list
- tuple
- string
- int
- float
- True
- False
- None
Python objects and their equivalent conversion to JSON:
Python | JSON Equivalent |
---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True | true |
False | false |
None | null |
Converting to JSON string
dumps() method can convert a Python object into a JSON string.
Syntax:
json.dumps(dict, indent)
It takes two parameters:
- dictionary: name of dictionary which should be converted to JSON object.
- indent: defines the number of units for indentation
Example: Converting Python dictionary to JSON string
Python3
# Python program to convert
# Python to JSON
import json
# Data to be written
dictionary = {
"name": "sunil",
"department": "HR",
"Company": 'GFG'
}
# Serializing json
json_object = json.dumps(dictionary)
print(json_object)
Output{"name": "sunil", "department": "HR", "Company": "GFG"}
Note: For more information about converting JSON to string, refer to Python - Convert to JSON string
Writing to a JSON file
dump() method can be used for writing to JSON file.
Syntax:
json.dump(dict, file_pointer)
It takes 2 parameters:
- dictionary: name of a dictionary which should be converted to a JSON object.
- file pointer: pointer of the file opened in write or append mode.
Example: Writing to JSON File
Python3
# Python program to write JSON
# to a file
import json
# Data to be written
dictionary ={
"name" : "Nisha",
"rollno" : 420,
"cgpa" : 10.10,
"phonenumber" : "1234567890"
}
with open("sample.json", "w") as outfile:
json.dump(dictionary, outfile)
Output:

Formatting JSON
In the above example, you must have seen that when you convert the Python object to JSON it does not get formatted and output comes in a straight line. We can format the JSON by passing the indent parameter to the dumps() method.
Example: Formatting JSON
Python3
# Import required libraries
import json
# Initialize JSON data
json_data = '[ {"studentid": 1, "name": "Nikhil", "subjects": ["Python", "Data Structures"]},\
{"studentid": 2, "name": "Nisha", "subjects": ["Java", "C++", "R Lang"]} ]'
# Create Python object from JSON string
# data
data = json.loads(json_data)
# Pretty Print JSON
json_formatted_str = json.dumps(data, indent=4)
print(json_formatted_str)
Output[
{
"studentid": 1,
"name": "Nikhil",
"subjects": [
"Python",
"Data Structures"
]
},
{
"studentid": 2,
"name": "Nisha",
"subjects": [
"Java",
"C++",
"R Lang"
]
}
]
Note: For more information, refer to Pretty Print JSON in Python
Sorting JSON
We can sort the JSON data with the help of the sort_keys parameter of the dumps() method. This parameter takes a boolean value and returns the sorted JSON if the value passed is True. By default, the value passed is False.
Example: Sorting JSON
Python3
# Import required libraries
import json
# Initialize JSON data
json_data = '[ {"studentid": 1, "name": "Nikhil", "subjects":\
["Python", "Data Structures"], "company":"GFG"},\
{"studentid": 2, "name": "Nisha", "subjects":\
["Java", "C++", "R Lang"], "company":"GFG"} ]'
# Create Python object from JSON string
# data
data = json.loads(json_data)
# Pretty Print JSON
json_formatted_str = json.dumps(data, indent=4, sort_keys=True)
print(json_formatted_str)
Output[
{
"company": "GFG",
"name": "Nikhil",
"studentid": 1,
"subjects": [
"Python",
"Data Structures"
]
},
{
"company": "GFG",
"name": "Nisha",
"studentid": 2,
"subjects": [
"Java",
"C++",
"R Lang"
]
}
]
Similar Reads
Python JSON Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called JSON. This package provides all the necessary tools for working with JSON Objects i
3 min read
json.loads() in Python JSON is a lightweight data format used for storing and exchanging data across systems. Python provides a built-in module called json to work with JSON data easily. The json.loads() method of JSON module is used to parse a valid JSON string and convert it into a Python dictionary. For example:Pythoni
4 min read
Why is Python So Popular? One question always comes into people's minds Why Python is so popular? As we know Python, the high-level, versatile programming language, has witnessed an unprecedented surge in popularity over the years. From web development to data science and artificial intelligence, Python has become the go-to
7 min read
Python Tkinter Python Tkinter is a standard GUI (Graphical User Interface) library for Python which provides a fast and easy way to create desktop applications. Tkinter provides a variety of widgets like buttons, labels, text boxes, menus and more that can be used to create interactive user interfaces. Tkinter sup
12 min read
Integrating Java with Python While programming in a language, a developer may feel the need to use some functionality that may have better support in another language. For example, suppose, an application has already been developed in Java, and we wish to use it in Python code. To invoke an existing Java application in Python,
4 min read
Best way to learn python Python is a versatile and beginner-friendly programming language that has become immensely popular for its readability and wide range of applications. Whether you're aiming to start a career in programming or just want to expand your skill set, learning Python is a valuable investment of your time.
11 min read
How to Learn Python Basics With ChatGPT Python is one of the most popular programming languages, known for its simplicity and versatility. Whether you're a complete beginner or an experienced programmer looking to expand your skillset, mastering the basics of Python is essential. In this guide, we'll walk you through the fundamentals of P
4 min read
JSON Formatting in Python JSON (JavaScript Object Notation) is a popular data format that is used for exchanging data between applications. It is a lightweight format that is easy for humans to read and write, and easy for machines to parse and generate. Python Format JSON Javascript Object Notation abbreviated as JSON is a
3 min read
Python A-Z Quick Notes Python is a general-purpose, high-level, interpreted programming language that supports multiple programming paradigms, including procedural, object-oriented, and functional programming, and is widely used among the developersâ community. Python was mainly developed for emphasis on code readability,
15+ min read
Python 3 basics Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it's not compiled and the interpreter will check the code line by line. This article can be used to learn the
10 min read