Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Serialize and Deserialize complex JSON in Python
Next article icon

Serialize and Deserialize complex JSON in Python

Last Updated : 18 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

  • JSON with Python
  • Read, Write, and Parse JSON using Python
  • Working With JSON Data in Python
  • JSON Formatting in Python

Next Article
Serialize and Deserialize complex JSON in Python

S

samrat2825
Improve
Article Tags :
  • Python
  • Python-json
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences