Backend Development 4 min read

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.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using the default Parameter in Python's json Module for Custom Serialization

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.

PythonSerializationJSONDateTimecustom-encoderdefault-parameter
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.