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
Working With JSON Data in Python
JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The tex
6 min read
Web crawling with Python
Web crawling is widely used technique to collect data from other websites. It works by visiting web pages, following links and gathering useful information like text, images, or tables. Python has various libraries and frameworks that support web crawling. In this article we will see about web crawl
4 min read
json.load() in Python
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Pytho
3 min read
What Can I Do With Python?
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Let's see what Python programming does: Uses of PythonIn terms of
5 min read
json.dump() in Python
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json . To use this feature, we import the json package in Pyth
6 min read
Interact with files in Python
Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complica
6 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
Python vs Cpython
Python is a high-level, interpreted programming language favored for its readability and versatility. It's widely used in web development, data science, machine learning, scripting, and more. However, Cpython is the default and most widely used implementation of the Python language. It's written in
4 min read
json.dumps() in Python
JSON is an acronym that stands for JavaScript Object Notation. Despite its name, JSON is a language agnostic format that is most commonly used to transmit data between systems, and on occasion, store data. Programs written in Python, as well as many other programming languages, can ingest JSON forma
6 min read