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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read