In this lesson, you will learn how to bridge the gap between Python’s custom class instances and the JSON format by implementing specialized encoder and decoder hooks.
The Serialization Challenge
The standard json library is great at handling native types like lists, strings, and dictionaries, but it doesn't know how to handle your custom objects. If you try to run json.dumps(my_object), Python will raise a TypeError because it doesn’t know which attributes should be saved or how to represent them in JSON.
Using default for Encoding
To fix this, we provide a default function to json.dumps. This function acts as a fallback: whenever the encoder encounters an object it doesn't recognize, it passes that object to your function, which should return a JSON-serializable dictionary.
import json
class User:
def __init__(self, name, role):
self.name = name
self.role = role
def user_to_dict(obj):
if isinstance(obj, User):
return {"name": obj.name, "role": obj.role}
raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")
user = User("Alice", "Admin")
json_data = json.dumps(user, default=user_to_dict)
print(json_data) # {"name": "Alice", "role": "Admin"}
Using object_hook for Decoding
Conversely, when reading JSON back into Python, you can use the object_hook argument in json.loads. This function intercepts every dictionary created during decoding and allows you to transform it back into an instance of your class:
def dict_to_user(data):
if "role" in data:
return User(data["name"], data["role"])
return data
user_obj = json.loads(json_data, object_hook=dict_to_user)
print(user_obj.name) # Alice
Why this matters
By decoupling your class structure from your storage format using these hooks, you can keep your data models clean while ensuring they remain perfectly compatible with external systems and configuration files. You aren't just saving data; you are defining a formal contract for how your Python objects are represented in the outside world.
Key Takeaway: By passing custom default and object_hook functions to json.dumps and json.loads, you can precisely control how your Python objects are serialized to and from JSON without modifying the objects themselves.