Saturday, November 16, 2024
Google search engine
HomeLanguagesJSON with Python

JSON with Python

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))


Output

Data 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.

read json Python

 

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:

Python write json to file

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"
        ]
    }
]
RELATED ARTICLES

Most Popular

Recent Comments