The Wayback Machine - https://web.archive.org/web/20241118195034/https://www.geeksforgeeks.org/encoding-and-decoding-custom-objects-in-python-json/
Open In App

Encoding and Decoding Custom Objects in Python-JSON

Last Updated : 10 Jul, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Similar Reads

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 encode and decode binary and text data. Base64 encodin
4 min read
How Do I Perform HTML Decoding/Encoding Using Python/Django?
HTML (HyperText Markup Language) is used for creating webpages. Sometimes, we need to make sure that special characters in this HTML are displayed correctly. For example, characters like <, >, and & have special meanings in HTML, so they need to be encoded (converted to a special format) when displayed as plain text. Sometimes, we may als
4 min read
Elias Delta Decoding in Python
In this article, we are going to implement Elias Delta Decoding using python. Peter Elias devised the Elias delta code, which is a universal system for encoding positive integers. Syntax: Elias Delta Encoding(X)= Elias Gamma encoding (1+floor(log2(X))) + Binary representation of X without MSB. Approach:Import required libraries and read the encoded
2 min read
Elias Gamma Decoding in Python
The Elias gamma code is a universal code that is used to encode a sequence of positive integers. It is developed by Peter Elias. It is most useful when the upper-bound of integers cannot be determined beforehand. Formula: Elias Gamma Coding=Unary(1+floor(log2(x)))+Binary representation of 'x' without MSB Example: Let’s consider an example where we
2 min read
Coding Decoding Question and Answers
Coding decoding is an important part of the Quantitative Aptitude section in most of the competitive examinations in India.  Coding and decoding questions are a common feature in the reasoning ability section of major Government exams such as those conducted by banks, insurance companies, SSC, and RRB. Prerequisites: Coding-Decoding - Tricks Sample
3 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
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 module comes in-built with Python standard module
3 min read
How to compare JSON objects regardless of order in Python?
JSON is Java Script Object Notation. These are language independent source codes used for data exchange and are generally lightweight in nature. It acts as an alternative to XML. These are generally texts which can be read and written easily by humans and it is also easier for machines to parse JSON and generate results. JSON is being used primaril
2 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 parameter is used so that, when we execute json.loads(),
2 min read
json.loads() vs json.loads() in Python
orjson.loads() and json.loads() are both Python methods used to deserialize (convert from a string representation to a Python object) JSON data. orjson and json are both Python libraries that provide functions for encoding and decoding JSON data. However, they have some differences in terms of performance and compatibility. json is a built-in Pytho
4 min read
How to return custom JSON in Django REST Framework ?
In this article, we will create class-based views and combine this with the serializer class to return JSON representation for each HTTP request. For our class-based views, we will make use of a set of generic views, which help to achieve minimum lines code. Generic Classes and ViewsetsHTTP requests to interact with relationship resourcesGeneric Cl
9 min read
Python | C Strings of Doubtful Encoding | Set-2
String handling in extension modules is a problem. C strings in extensions might not follow the strict Unicode encoding/decoding rules that Python normally expects. Thus, it’s possible that some malformed C data would pass to Python. A good example might be C strings associated with low-level system calls such as filenames. For instance, what happe
3 min read
Python | C Strings of Doubtful Encoding | Set-1
One can convert strings between C and Python vice-versa but the C encoding is of a doubtful or unknown nature. Let's suppose that a given C data is supposed to be UTF-8, but it’s not being strictly enforced. So, it is important to handle such kind of malformed data so that it doesn’t crash Python or destroy the string data in the process. Code#1 :
2 min read
Python | Character Encoding
Finding the text which is having nonstandard character encoding is a very common step to perform in text processing. All the text would have been from utf-8 or ASCII encoding ideally but this might not be the case always. So, in such cases when the encoding is not known, such non-encoded text has to be detected and the be converted to a standard en
2 min read
Elias Gamma Encoding in Python
The Elias gamma code is a universal code that is used to encode a sequence of positive integers. It is developed by Peter Elias. It is most useful when the upper bound of integers cannot be determined beforehand. Steps in Encoding: To encode a number X, Find the largest N, with [Tex]2^{N}\leq X[/Tex](greater power of 2). Encode N using Unary coding
1 min read
Resolve "No Module Named Encoding" in Python
One common error that developers may encounter is the "No Module Named 'Encodings'" error. This error can be frustrating, especially for beginners, but understanding its origins and learning how to resolve it is crucial for a smooth Python development experience. What is Module Named 'Encodings'?The error message "No Module Named 'Encodings'" indic
3 min read
Detect Encoding of a Text file with Python
Python provides a straightforward way to determine the encoding of a text file, essential for the proper handling of diverse character sets. The chardet library is a popular choice for automatic character encoding detection. By analyzing the statistical distribution of byte values, it accurately identifies the encoding scheme used in a given text f
2 min read
How to Fix TypeError: String Argument Without an Encoding in Python
The TypeError: string argument without an encoding is a common error that arises when working with the string encoding in Python. This error typically occurs when attempting to the convert a string to the bytes without specifying the necessary encoding. In this article, we will explore the causes of this error and provide the practical solutions to
3 min read
response.encoding - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.encoding out of a
2 min read
Run Length Encoding in Python
Given an input string, write a function that returns the Run Length Encoded string for the input string. For example, if the input string is 'wwwwaaadexxxxxx', then the function should return 'w4a3d1e1x6'. Examples: Input : str = 'wwwwaaadexxxxxx'Output : 'w4a3d1e1x6'This problem has existing solution please refer Run Length Encoding link. Here we
2 min read
Elias Delta Encoding in Python
In this article, we are going to implement Elias Delta encoding using python. Syntax: Elias Delta Encoding(X)= Elias Gamma encoding (1+floor(log2(X))) + Binary representation of X without MSB. ImplementationFirst, we are going to implement Elias delta Encoding, Before writing code for Elias Delta Encoding. Step 1: Import log, floor functions from t
3 min read
Encoding in BeautifulSoup
The character encoding plays a major role in the interpretation of the content of an HTML and XML document. A document does not only contain English characters but also non-English characters like Hebrew, Latin, Greek and much more. To let the parser know, which encoding method should be used, the documents will contain a dedicated tag and attribut
6 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Python: Difference between Lock and Rlock objects
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System). In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other codes. For simplicity, you can assume that a thread is si
5 min read
Addition and Subtraction on TimeDelta objects using Pandas - Python
TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. Operations on TimeDelta dataframe or series - 1) Addition - df['Result'] = df['TimeDelta1']
2 min read
How to get the list of all initialized objects and function definitions alive in Python?
In this article, we are going to get the list of all initialized objects and function definitions that are alive in Python, so we are getting all those initialized objects details by using gc module we can get the details. GC stands for garbage collector which is issued to manage the objects in the memory, so from that module, we are using the get_
2 min read
Python Classes and Objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it to maintain its state. Class instances can als
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg