VOOZH about

URL: https://www.geeksforgeeks.org/python/convert-json-data-into-a-custom-python-object/

⇱ Convert JSON data Into a Custom Python Object - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert JSON data Into a Custom Python Object

Last Updated : 3 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.

Output: 

πŸ‘ jsonOriginal
Namedtuple

Explanation: 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().

Output:

πŸ‘ jsonCd1
Custom Decoder

Example 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.

Output:

πŸ‘ jsonNamespace1
Namespace
Comment
Article Tags: