Convert JSON data Into a Custom Python Object
Last Updated :
03 Jul, 2025
In Python, converting JSON data into a custom object is known as decoding or deserializing JSON data. We can easily convert JSON data into a custom object by using the json.loads() or json.load() methods. The key is the object_hook parameter, which allows us to define how the JSON data should be converted into a custom Python object.
object_hook parameter is used to customize the deserialization process. By providing a custom function to this parameter, we can convert the JSON data into custom Python objects.
Let's look at some of the examples:
Example 1: Using namedtuple for Custom Objects
namedtuple from the collections module creates a class with fields that can be accessed by name, providing an easy way to treat JSON data as a Python object.
Python
import json
from collections import namedtuple
# Sample JSON data
data = '{"name": "Geek", "id": 1, "location": "Mumbai"}'
# Convert JSON into a namedtuple object
x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
# Accessing data like an object
print(x.name, x.id, x.location)
Output:
NamedtupleExplanation: the namedtuple allows us to treat the JSON data as an object, where we can access values by their keys as attributes.
Example 2: Using a Custom Decoder Function
We can also write a custom decoder function that converts the JSON dictionary into a custom Python object type, and use this function with json.loads().
Python
import json
from collections import namedtuple
# Custom decoder function
def customDecoder(geekDict):
return namedtuple('X', geekDict.keys())(*geekDict.values())
# Sample JSON data
geekJsonData = '{"name": "GeekCustomDecoder", "id": 2, "location": "Pune"}'
# Use custom decoder to parse the JSON data
x = json.loads(geekJsonData, object_hook=customDecoder)
print(x.name, x.id, x.location)
Output:
Custom DecoderExample 3: Using SimpleNamespace for Simplicity
SimpleNamespace from the types module provides a simpler alternative to namedtuple. It doesn’t require creating a class for each object, which can improve performance.
Python
import json
from types import SimpleNamespace as Namespace
# Sample JSON data
data = '{"name": "GeekNamespace", "id": 3, "location": "Bangalore"}'
# Use SimpleNamespace to create a custom object
x = json.loads(data, object_hook=lambda d: Namespace(**d))
# Accessing the data
print(x.name, x.id, x.location)
Output:
Namespace