Fallback Serialization Function

Purpose

When serializing Python objects to JSON, some data types may not have a direct JSON representation or built-in serialization support. The **Fallback Serialization Function** addresses this challenge by allowing users to define a custom handler that converts unsupported Python objects into JSON-serializable forms. This mechanism ensures that complex or user-defined types do not cause serialization failures, enabling graceful handling or transformation of these objects during the serialization process.

Functionality

This feature works by accepting a user-provided fallback function (commonly named `default`) that is invoked whenever the serializer encounters an object it cannot serialize natively. The fallback function receives the unsupported object and is expected to return a JSON-serializable representation or raise an exception if it cannot handle the type.

Key behaviors include:

A typical usage pattern from the benchmark script demonstrates this:

from orjson import dumps, OPT_SERIALIZE_NUMPY

class Custom:
    pass

def default(_):
    return None  # Provide a fallback JSON-compatible value

obj = [[Custom()] * 1000] * 10
result = dumps(obj, default, OPT_SERIALIZE_NUMPY)

In this example, instances of `Custom` are not natively serializable, so the `default` function returns `None` as their JSON representation.

Integration

The fallback serialization function is an extension point within the broader **Custom Serialization Support** topic. It complements other subtopics such as **Numpy Serialization** by providing a generic mechanism to handle any unsupported Python object types, not just numpy arrays.

Within the serialization workflow:

This fallback approach enhances robustness and user control, enabling serialization of complex, nested, or application-specific data structures without modifying the core library.

Process Flow Diagram

flowchart TD
    A[Start Serialization] --> B{Is Object Supported?}
    B -- Yes --> C[Serialize Object]
    B -- No --> D[Call Fallback Function]
    D --> E{Fallback Returns Serializable?}
    E -- Yes --> F[Serialize Fallback Result]
    E -- No --> G[Raise Serialization Error]
    C --> H[Continue Serialization]
    F --> H
    G --> I[Serialization Fails]
    H --> J[End Serialization]

This flowchart illustrates the decision process during serialization when an unsupported object type is encountered and how the fallback function is invoked to provide a serializable representation.