Custom JSON Encoding
When you try to serialize types JSON doesn't support (dates, sets, custom objects), you need a custom encoder.
import json
from datetime import datetime
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
Use it with the cls parameter:
data = {"event": "meeting", "when": datetime.now()}
json.dumps(data, cls=CustomEncoder)
# '{"event": "meeting", "when": "2023-08-06T14:30:00"}'
For simpler cases, use the default parameter:
def convert(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Can't serialize {type(obj)}")
json.dumps(data, default=convert)
The encoder handles each unserializable object and returns something JSON can understand.
I cover custom encoding in my JSON with Python course.