Serialize Python Datetime, Set, Path, and Enum Types Safely with JSON
Robust Serialization with JSON and Custom Types
By Iván Palomares Carrascosa · October 26, 2026 · Practical Python
JSON’s limits tend to surface in the unglamorous work that keeps machine learning systems running: moving configuration and data between files, processes, services, and APIs. A model may be the headline, but the plumbing around it is where ordinary Python objects can break the pipeline.
This section introduces a practical approach to serializing custom types and restoring them later, handling malformed input gracefully, and adapting to schema changes with defaults and migrations. The examples focus on datetime, set, Path, and Enum. If you’re building pipelines that pass structured data between components, this is a reliability problem worth solving early.
- Build a custom JSON encoder for Python types such as
datetime,set,Path, andEnum. - Write a decoder that reconstructs those objects from JSON and can respond gracefully to malformed data.
- Use a factory function to apply defaults and migrations as schemas change.

Why plain JSON falls short
Consider a machine learning experiment configuration containing an ID, a model choice, selected features, a data file path, a timestamp, and nested retry metadata. Python can represent all of those naturally. JSON can’t represent every one of them directly.
from datetime import datetime
from enum import Enum
from pathlib import Path
import json
class ModelType(Enum):
RANDOM_FOREST = "rf"
NEURAL_NET = "nn"
experiment_config = {
"experiment_id": 1042,
"model_type": ModelType.NEURAL_NET,
"features": {"age", "income", "location"}, # A set!
"data_path": Path("/data/v2/train.csv"),
"timestamp": datetime.now(),
"nested_meta": {
"retries": 3
}
}Try passing this dictionary to json.dumps(experiment_config) and serialization fails immediately:
TypeError: Object of type ModelType is not JSON serializableThat error names the enum, but the underlying issue applies to the other custom values too: standard JSON encoding doesn’t know how to preserve their Python types. A successful pipeline needs to decide how to represent each value in JSON, then define how to rebuild it on the way back. That said, recovering the values is only part of the job; stored data can outlive the schema that first produced it, and malformed records shouldn’t necessarily take down the entire pipeline.
1. Handling Types the JSON Encoder Doesn’t Know
The ModelType serialization error points to a gap in Python’s standard JSON support: objects such as datetimes, sets and paths need an explicit conversion rule. A custom encoder gives you one place to define those rules while leaving ordinary JSON values to the standard library.
Subclass json.JSONEncoder and override default(). That method can inspect each unsupported object with isinstance(), convert recognized types, and pass anything else back to the base implementation. The fallback matters: unsupported objects should still raise the usual TypeError, rather than being silently transformed.
class RobustEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return {"__type__": "datetime", "value": obj.isoformat()}
if isinstance(obj, set):
return {"__type__": "set", "value": list(obj)}
if isinstance(obj, Path):
return {"__type__": "path", "value": str(obj)}
if isinstance(obj, Enum):
return obj.value
return super().default(obj)
json_string = json.dumps(experiment_config, cls=RobustEncoder, indent=2)
print(json_string)The type markers are doing useful work here. Turning a set into a list makes it acceptable to JSON, but also erases the fact that it started as a set. The __type__ field preserves that clue for a decoder. Datetimes and paths get similar markers; enum values are emitted directly, so their original enum type isn’t retained by this example.
Passing cls=RobustEncoder to json.dumps() activates the custom rules. For the example configuration, the output looks like this:
{
"experiment_id": 1042,
"model_type": "nn",
"features": {
"__type__": "set",
"value": [
"income",
"location",
"age"
]
},
"data_path": {
"__type__": "path",
"value": "/data/v2/train.csv"
},
"timestamp": {
"__type__": "datetime",
"value": "2026-09-28T14:26:10.328310"
},
"nested_meta": {
"retries": 3
}
}