Serialize and Deserialize complex JSON in Python
Last Updated : 18 Jan, 2024
JSON stands for JavaScript Object Notation. It is a format that encodes the data in string format. JSON is language-independent and because of that, it is used for storing or transferring data in files.
Serialization of JSON object: It means converting a Python object (typically a dictionary) into a JSON formatting string.
Deserialization of JSON object: It is just the opposite of serialization, meaning converting a JSON-formatted string back to a Python Object.
JSON Object is defined using curly braces{} and consists of a key-value pair. It is important to note that the JSON object key is a string and its value can be any primitive(e.g. int, string, null) or complex data type (e.g. array).
Example of JSON Object:
{
"id":101,
"company" : "GeeksForGeeks"
}
Complex JSON objects are those objects that contain a nested object inside the other. Example of Complex JSON Object.
{
"id":101,
"company" : "GeeksForGeeks",
"Topics" : { "Data Structure",
"Algorithm",
"Gate Topics" }
}
Serialization and Deserialization of JSON Object
Python and the JSON module work exceptionally well with dictionaries. For serializing and deserializing JSON objects in Python, you can utilize the "__dict__ "attribute available on many Python objects.
This attribute is a dictionary used to store an object's writable attributes. You can leverage this attribute effectively when working with JSON data, making the process seamless and efficient.
Code:
Python3 import json class GFG_User(object): def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name user = GFG_User(first_name="Jake", last_name="Doyle") json_data = json.dumps(user.__dict__) print(json_data) print(GFG_User(**json.loads(json_data)))
Output:
{"first_name": "Jake", "last_name": "Doyle"}
__main__.GFG_User object at 0x105ca7278
Note: The double asterisks ** in the GFG_User(**json.load(json_data) line may look confusing. But all it does is expand the dictionary.
Serialization and Deserialization of Complex JSON Objects
Now things get tricky while dealing with complex JSON objects as our trick "__dict__" doesn't work anymore.
Code:
Python3 from typing import List import json class Student(object): def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name class Team(object): def __init__(self, students: List[Student]): self.students = students student1 = Student(first_name="Geeky", last_name="Guy") student2 = Student(first_name="GFG", last_name="Rocks") team = Team(students=[student1, student2]) json_data = json.dumps(team.__dict__, indent=4) print(json_data)
Output:
TypeError: Object of type Student is not JSON serializable
But if you look at the documentation of the dump function you will see there is a default setting that we can use. Simply by replacing the line:
json_data = json.dumps(team.__dict__, indent=4)
to this line:
json_data = json.dumps(team.__dict__, default=lambda o: o.__dict__, indent=4)
And everything works now as before. Now, let's look at code of serializing and deserializing complex object:
Code:
The code defines two classes, Student
and Team
. The serialization process converts the team
object into a JSON string, using a lambda function to transform the objects into dictionaries for JSON compatibility and then deserializes them back into Python objects.
Python3 from typing import List import json class Student(object): def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name class Team(object): def __init__(self, students: List[Student]): self.students = students student1 = Student(first_name="Geeky", last_name="Guy") student2 = Student(first_name="GFG", last_name="Rocks") team = Team(students=[student1, student2]) # Serialization json_data = json.dumps(team, default=lambda o: o.__dict__, indent=4) print(json_data) # Deserialization decoded_team = Team(**json.loads(json_data)) print(decoded_team)
Output:
{
"students": [
{
"first_name": "Geeky",
"last_name": "Guy"
},
{
"first_name": "GFG",
"last_name": "Rocks"
}
]
}
__main__.Team object at 0x105cd41d0
We have explained how to serialize and deserialize complex JSON objects in Python in easy words. This is a step-by-step tutorial to properly demonstrate the programs on how to serialize complex JSON and how to deserialize complex JSON.
Also Read:
Similar Reads
Modules available for Serialization and Deserialization in Python Python provides three different modules which allow us to serialize and deserialize objects : Â Marshal ModulePickle ModuleJSON Module 1. Marshal Module: It is the oldest module among these three. It is mainly used to read and write the compiled byte code of Python modules. Even we can use marshal t
3 min read
Deserialize JSON to Object in Python Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module
2 min read
Flask Serialization and Deserialization Serialization and deserialization are fundamental concepts in web development, especially when working with REST APIs in Flask. Serialization refers to converting complex data types (such as Python objects) into a format that can be easily stored or transmitted, like JSON or XML. Deserialization, on
4 min read
How to Fix - "datetime.datetime not JSON serializable" in Python? In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, wh
4 min read
Fetch JSON URL Data and Store in Excel using Python In this article, we will learn how to fetch the JSON data from a URL using Python, parse it, and store it in an Excel file. We will use the Requests library to fetch the JSON data and Pandas to handle the data manipulation and export it to Excel.Fetch JSON data from URL and store it in an Excel file
3 min read
Reading and Writing JSON to a File 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