Open In App

Convert JSON data Into a Custom Python Object

Last Updated : 16 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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(), the return value of object_hook will be used instead of the default dict value.We can also implement custom decoders using this.
Example 1 : 

Python3




# importing the module
import json
from collections import namedtuple
 
# creating the data
data = '{"name" : "Geek", "id" : 1, "location" : "Mumbai"}'
 
# making the object
x = json.loads(data, object_hook =
               lambda d : namedtuple('X', d.keys())
               (*d.values()))
 
# accessing the JSON data as an object
print(x.name, x.id, x.location)


Output : 

As we can see in the above example, the namedtuple is a class, under the collections module. It contains keys that are mapped to some values. In this case, we can access the elements using keys and indexes. We can also create a custom decoder function, in which we can convert dict into a custom Python type and pass the value to the object_hook parameter which is illustrated in the next example.
Example 2 :  

Python3




# importing the module
import json
from collections import namedtuple
 
# customDecoder function
def customDecoder(geekDict):
    return namedtuple('X', geekDict.keys())(*geekDict.values())
 
# creating the data
geekJsonData = '{"name" : "GeekCustomDecoder", "id" : 2, "location" : "Pune"}'
 
# creating the object
x = json.loads(geekJsonData, object_hook = customDecoder)
 
# accessing the JSON data as an object
print(x.name, x.id, x.location)


Output : 

We can also use SimpleNamespace class from the types module as the container for JSON objects. Advantages of a SimpleNamespace solution over a namedtuple solution: –

  1. It is faster because it does not create a class for each object.
  2. It is shorter and simpler.

Example 3 : 

Python3




# importing the module
import json
try:
    from types import SimpleNamespace as Namespace
except ImportError:
    from argparse import Namespace
 
# creating the data
data = '{"name" : "GeekNamespace", "id" : 3, "location" : "Bangalore"}'
 
# creating the object
x = json.loads(data, object_hook = lambda d : Namespace(**d))
 
# accessing the JSON data as an object
print(x.name, x.id, x.location)


Output : 



Previous Article
Next Article

Similar Reads

How to Convert Models Data into JSON in Django ?
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. How to Convert Models Data Into Json Data In Django ? First create new
2 min read
Python | Ways to convert string to json object
In this article, we will see different ways to convert string to JSON in Python this process is called serialization. JSON module provides functions for encoding (serializing) Python objects into JSON strings and decoding (deserializing) JSON strings into Python objects. Encoding (Serializing) JSON: If you have a Python object and want to convert i
3 min read
Convert class object to JSON in Python
Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object's attributes. Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is pas
2 min read
Convert HTML source code to JSON Object using Python
In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages. We will use xmltojson mo
3 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 methods. Convert Generator Object To JSON In PythonBelo
2 min read
Normalizing Nested Json Object Into Pandas Dataframe
The encapsulation of one or more JSON objects into another JSON object is called a nested JSON object. There are various circumstances when we have the data in JSON object form and have to imply numerous functions on the dataset. In such cases, we can use the Python library called Pandas which is used for datasets. For converting into a Pandas data
3 min read
How to convert pandas DataFrame into JSON in Python?
Data Analysis is an extremely important tool in today's world. A key aspect of Data Analytics is an organized representation of data. There are numerous data structures in computer science to achieve this task. In this article, we talk about two such data structures viz. Pandas DataFrame and JSON. Further, we see how to convert DataFrames to JSON f
4 min read
Convert a Bytes Array into Json Format in Python
In Python, dealing with bytes data is common, and converting a bytes array to JSON format is a frequent task. In this article, we will see how to convert a bytes array into JSON format in Python. Python Convert a Bytes Array into JSON FormatBelow are some of the ways by which we can convert a bytes array into JSON format in Python: Using decode and
3 min read
Encoding and Decoding Custom Objects in Python-JSON
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
5 min read
How to Parse Data From JSON into Python?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data from JSON and work with it. Before starting the det
2 min read
Practice Tags :
three90RightbarBannerImg