Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Convert JSON data Into a Custom Python Object
Next article icon

Encoding and Decoding Custom Objects in Python-JSON

Last Updated : 10 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it’s the most widely used format for the REST APIs.

Note: For more information, refer to Read, Write and Parse JSON using Python

Getting Started

Python provides a built-in json library to deal with JSON objects. All you need is to import the JSON module using the following line in your Python program and start using its functionality.

import json

Now the JSON module provides a lot of functionality and we’re going to discuss only 2 methods out of them. They are dumps and loads. The process of converting a python object to a json one is called JSON serialization or encoding and the reverse process i.e. converting json object to Python one is called deserialization or decoding

For encoding, we use json.dumps() and for decoding, we’ll use json.loads(). So it is obvious that the dumps method will convert a python object to a serialized JSON string and the loads method will parse the Python object from a serialized JSON string.

Note:

  • It is worth mentioning here that the JSON object which is created during serialization is just a Python string, that’s why you’ll find the terms “JSON object” and “JSON string” used interchangeably in this article
  • Also it is important to note that a JSON object corresponds to a Dictionary in Python. So when you use loads method, a Python dictionary is returned by default (unless you change this behaviour as discussed in the custom decoding section of this article)

Example:




import json
  
# A basic python dictionary
py_object = {"c": 0, "b": 0, "a": 0} 
  
# Encoding
json_string = json.dumps(py_object)
print(json_string)
print(type(json_string))
  
# Decoding JSON
py_obj = json.loads(json_string) 
print()
print(py_obj)
print(type(py_obj))
 
 

Output:

{"c": 0, "b": 0, "a": 0}  <class 'str'>    {'c': 0, 'b': 0, 'a': 0}  <class 'dict'>

Although what we saw above is a very simple example. But have you wondered what happens in the case of custom objects? In that case he above code will not work and we will get an error something like – TypeError: Object of type SampleClass is not JSON serializable. So what to do? Don’t worry we will get to get in the below section.

Encoding and Decoding Custom Objects

In such cases, we need to put more efforts to make them serialize. Let’s see how we can do that. Suppose we have a user-defined class Student and we want to make it JSON serializable. The simplest way of doing that is to define a method in our class that will provide the JSON version of our class’ instance.

Example:




import json
   
class Student:
    def __init__(self, name, roll_no, address):
        self.name = name
        self.roll_no = roll_no
        self.address = address
   
    def to_json(self):
        '''
        convert the instance of this class to json
        '''
        return json.dumps(self, indent = 4, default=lambda o: o.__dict__)
   
class Address:
    def __init__(self, city, street, pin):
        self.city = city
        self.street = street
        self.pin = pin
          
address = Address("Bulandshahr", "Adarsh Nagar", "203001")
student = Student("Raju", 53, address)
  
# Encoding
student_json = student.to_json()
print(student_json)
print(type(student_json))
  
# Decoding
student = json.loads(student_json)
print(student)
print(type(student))
 
 

Output:

{
“name”: “Raju”,
“roll_no”: 53,
“address”: {
“city”: “Bulandshahr”,
“street”: “Adarsh Nagar”,
“pin”: “203001”
}
}
<class ‘str’>

{‘name’: ‘Raju’, ‘roll_no’: 53, ‘address’: {‘city’: ‘Bulandshahr’, ‘street’: ‘Adarsh Nagar’, ‘pin’: ‘203001’}}
<class ‘dict’>

Another way of achieving this is to create a new class that will extend the JSONEncoder and then using that class as an argument to the dumps method.

Example:




import json
from json import JSONEncoder
  
class Student:
    def __init__(self, name, roll_no, address):
        self.name = name
        self.roll_no = roll_no
        self.address = address
  
  
class Address:
    def __init__(self, city, street, pin):
        self.city = city
        self.street = street
        self.pin = pin
  
class EncodeStudent(JSONEncoder):
        def default(self, o):
            return o.__dict__
              
address = Address("Bulandshahr", "Adarsh Nagar", "203001")
student = Student("Raju", 53, address)
  
# Encoding custom object to json
# using cls(class) argument of
# dumps method
student_JSON = json.dumps(student, indent = 4,
                          cls = EncodeStudent)
print(student_JSON)
print(type(student_JSON))
  
# Decoding
student = json.loads(student_JSON)
print()
print(student)
print(type(student))
 
 

Output:

{
“name”: “Raju”,
“roll_no”: 53,
“address”: {
“city”: “Bulandshahr”,
“street”: “Adarsh Nagar”,
“pin”: “203001”
}
}
<class ‘str’>

{‘name’: ‘Raju’, ‘roll_no’: 53, ‘address’: {‘city’: ‘Bulandshahr’, ‘street’: ‘Adarsh Nagar’, ‘pin’: ‘203001’}}
<class ‘dict’>

For Custom Decoding, if we want to convert the JSON into some other Python object (i.e. not the default dictionary) there is a very simple way of doing that which is using the object_hook parameter of the loads method. All we need to do is to define a method that will define how do we want to process the data and then send that method as the object_hook argument to the loads method, see in given code. Also, the return type of load will no longer be the Python dictionary. Whatever is the return type of the method we’ll pass in as object_hook, it will also become the return type of loads method. This means that in following example, complex number will be the return type.




import json
  
  
def as_complex(dct):
      
    if '__complex__' in dct:
        return complex(dct['real'], dct['imag'])
      
    return dct
  
res = json.loads('{"__complex__": true, "real": 1, "imag": 2}',
           object_hook = as_complex)
print(res)
print(type(res))
 
 

Output:

(1+2j)  <class 'complex'>


Next Article
Convert JSON data Into a Custom Python Object

V

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

Similar Reads

  • Flattening JSON objects in Python
    JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This
    3 min read
  • Convert JSON data Into a Custom Python Object
    Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parame
    2 min read
  • Encoding and Decoding Base64 Strings in Python
    The Base64 encoding is used to convert bytes that have binary or text data into ASCII characters. Encoding prevents the data from getting corrupted when it is transferred or processed through a text-only system. In this article, we will discuss about Base64 encoding and decoding and its uses to enco
    4 min read
  • Convert class object to JSON in Python
    In Python, class objects are used to organize complex information. To save or share this information, we need to convert it into a format like JSON, which is easy to read and write. Since class objects can't be saved directly as JSON, we first convert them into a dictionary (a data structure with ke
    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
  • Convert Generator Object To JSON In Python
    JSON (JavaScript Object Notation) is a widely used data interchange format, and Python provides excellent support for working with JSON data. However, when it comes to converting generator objects to JSON, there are several methods to consider. In this article, we'll explore some commonly used metho
    2 min read
  • How to return a json object from a Python function?
    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 and this module can be used to convert a python dictionar
    2 min read
  • Creating nested dataclass objects in Python
    Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes. Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special method
    3 min read
  • How to JSON decode in Python?
    When working with JSON data in Python, we often need to convert it into native Python objects. This process is known as decoding or deserializing. The json module in Python provides several functions to work with JSON data, and one of the essential tools is the json.JSONDecoder() method. This method
    5 min read
  • Python Encode Unicode and non-ASCII characters into JSON
    This article will provide a comprehensive guide on how to work with Unicode and non-ASCII characters in Python when generating and parsing JSON data. We will look at the different ways to handle Unicode and non-ASCII characters in JSON. By the end of this article, you should have a good understandin
    5 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