Using the default Parameter in Python's json Module for Custom Serialization
This article explains how the json module's default parameter can be used to serialize unsupported Python objects, such as datetime, by providing a custom function or by subclassing JSONEncoder, and includes clear code examples demonstrating both approaches.
In Python's json module, the default parameter allows you to define how objects that are not natively serializable are converted to JSON.
By passing a custom function to json.dumps() or by subclassing json.JSONEncoder and overriding its default() method, you can handle types such as datetime.
Example using a function:
import json
from datetime import datetime
data = {"time": datetime.now()}
def custom_serializer(obj):
"""Custom serialization function"""
if isinstance(obj, datetime):
return obj.isoformat() # Convert datetime to ISO string
raise TypeError(f"{type(obj)} not serializable")
json_str = json.dumps(data, default=custom_serializer)
print(json_str) # {"time": "2025-05-07T16:39:45.123456"}Example by subclassing JSONEncoder:
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json_str = json.dumps(data, cls=CustomEncoder)
print(json_str) # {"time": "2025-05-07T16:39:45.123456"}The default approach greatly expands the json module's capabilities, enabling serialization of a broader range of data structures while ensuring that unsupported types ultimately raise appropriate errors.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
