JSON is a subset of JavaScript that is used to transmit data between the server and client in a structured format. JSON package is built in Python. So, JSON data can be easily encoded and decode by using Python script by importing the JSON package. Primitive data types like string, number and compound data types like list, objects, etc. are supported by JSON. How JSON data can be parsed and processed using Python script is shown in this tutorial.

Serialization and Deserialization

Python object translates into a JSON object by using serialization and the JSON object translates into a Python object by using deserialization. The following table shows how Python objects are converted to JSON objects or vice versa during the time of serialization and deserialization.

JSON    Python
true true
false false
string string
number number
array list, tuple
object dict
null none

Methods:

load()     : This method is used to load data from a JSON file into a python dict.


Loads( ) : This method is used to load data from a JSON variable into a python dict.


dump()  :  This method is used to load data from the python dictionary to the JSON file.


dumps(): This method is used to load data from the python dictionary to the JSON variable.

Reading JSON data using Python

JSON data can be parsed and processed in various ways by using Python script. How different types of JSON data can be parsed are shown in this part by using different Python examples. Create a simple json file named student.json with the following data to test the scripts of this tutorial.

[ {“ID”: “1110978”,“Name”: “Alif al Razi”, “Batch”: “34”,   “Semester”: “8”,


 “Department”: “CSE”},

{“ID”: “2220998”,“Name”: “Nusrat Faria”, “Batch”: “23”, “Semester”: “9”,


 “Department”: “BBA”},

{“ID”: “1118934”,“Name”: “Emran Hossain”, “Batch”: “33”, “Semester”: “7”,

“Department”: “CSE”},

{“ID”: “4448934”,“Name”: “Rehana Akter”, “Batch”: “41”, “Semester”: “10”,

“Department”: “ENG”},

{“ID”: “11107745”,“Name”: “Saif Ali”, “Batch”: “39”, “Semester”: “5”,

“Department”: “CSE”}]

Example 1: Read and print a JSON file in JSON format

Create a python file named json1.py with the following script. JSON module is used to read any JSON data using python script. open() method is used to read student.json file and load() method is used to store the data into the variable, data.

# Import JSON module

import json

# Open the existing JSON file for loading into a variable


with open(‘student.json’) as f:


  data = json.load(f)

# Print the JSON data


print(data)

Output:

The following output will appear after running the script.

How to parse and process JSON in Python JSON Python

Example 2: Read and parse data from a JSON file using Python dict

JSON data can be stored in any python dictionary variable to process each property value easily later. Create a python script named json2.py with the following code. The previously created json file is used here. After loading the data into the dictionary, each property value of each record will be printed by using property name.

# Import json module

import json

# Open the existing json file for loading into a variable


with open(‘student.json’, ‘r’) as f:


  students = json.load(f)

# Print each property of the object

for student in students:


  print(student[‘Name’],‘,’,student[‘Batch’],‘batch’,‘,’,  student[‘Semester’],

‘Semester’,‘,’,student[‘Department’],‘department’)

Output:

The following output will appear after running the script.

How to parse and process JSON in Python JSON Python

Example 3: Parse a JSON data

JSON data can be parsed from any JSON variable. Create a file named json3.py with the following script. JSONData is declared here to store JSON data of three properties. loads() method is used here to load data from a JSON variable. Next, each property value with each property name will print line by line in the terminal.

# Import json module

import json

# Define json data


JSONData = ‘{“Java”: “3 Credits”, “PHP”: “2 Credits”, “C “: “3 Credits”}’

# Load the json data into a variable


storedata = json.loads(JSONData)

# Iterate the for loop to print the data with key

for val in storedata:


  print(“%s: %s” % (val, storedata[val]))

Output:

The following output will appear after running the script.

How to parse and process JSON in Python JSON Python

Example 4: Parse JSON data into a Python object

JSON data are stored in a python dictionary variable in the previous three examples of this tutorial. This example shows how you can store JSON data into any python object. Create a file named json4.py with the following script. Here, read_data class is used to store JSON data into an object. JSONData, a variable is used when creating the object of the class. Three properties exist in the JSONData and the value of the property name, PHP will print as output.

# Import JSON module

import json

# Define JSON data


JSONData = ‘{“Java”: “3 Credits”, “PHP”: “2 Credits”, “C “: “3 Credits”}’

# Declare class to store JSON data into a python dictionary

class read_data(object):


  def __init__(self, jdata):


    self.__dict__ = json.loads(jdata)

# Assign object of the class


p_object = read_data(JSONData)

# Print the value of specific property


print(p_object.PHP)

Output:

The value of the ‘PHP’ property is ‘2 credits’. So, the following output will appear after running the script.

How to parse and process JSON in Python JSON Python

Example 5: Converting Python dict to JSON data

JSON data are stored in Python dictionary or object in the previous examples but the data from the python dictionary can also be stored into a JSON variable. Create a file named json5.py with the following script. The data are stored in the dictionary variable, customerDict.  dumps() method is used here to convert the data from a dictionary variable to a JSON variable, jsonObject. Next, the value of the JSON variable is printed as output.

# Import JSON module

import json

# Declare a python dictionary


customerDict = {‘name’: ‘John’, ‘type’: ‘gold’, ‘age’: 35 }

# Load the data from dictionary to JSON object


jsonData = json.dumps(customerDict)

# Print the JSON object


print(jsonData)

Output:

The following output will appear after running the script.

How to parse and process JSON in Python JSON Python

Conclusion:

JSON data format is supported by many programming languages. The conversion of JSON to Python and python to JSON data are explained in this tutorial by using various python examples. You will be able to perform any type of data conversion from python object to JSON object or vice versa after practicing this tutorial.

About the author

How to parse and process JSON in Python JSON Python

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.