The currently accepted solution using a MultipleJsonEncoders
class works but somewhat abuses the interface, because functions like json.dumps
really should be passed an instance of json.JSONEncoder
. This becomes apparent when you start writing type annotations for surrounding code.
To do this with proper typing you can do something similar to the MultipleJsonEncoder
solution, but wrapping the class in an abstract factory method that produces a properly typed JSONEncoder subclass as the "multi encoder":
def multiencoder_factory(*encoders):
class MultipleJsonEncoders(json.JSONEncoder):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.encoders = [encoder(*args, **kwargs) for encoder in encoders]
def default(self, o):
for encoder in self.encoders:
try:
return encoder.default(o)
except TypeError:
pass
return super().default(o)
return MultipleJsonEncoders
this produces the desired behavior when serializing objects via multiple encoders. For example:
import json
import enum
import datetime
class JsonDateEncoder(json.JSONEncoder):
"""JSON serializer for objects not serializable by default json code"""
def default(self, o):
if isinstance(o, (datetime.datetime, datetime.date)):
return o.isoformat()
return super().default(o)
class JsonEnumEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, enum.Enum):
return o.name
return super().default(o)
class Enumm(enum.Enum):
X = enum.auto()
obj = {'time': datetime.datetime.now(), 'enum': Enumm.X}
encoder = multiencoder_factory(JsonDateEncoder, JsonEnumEncoder)
json.dumps(obj, cls=encoder)
produces '{"time": "2023-08-18T11:23:26.626274", "enum": "X"}'
.
Not only that but encoder
is a valid subclass of json.JSONEncoder
as we expect
In [2]: isinstance(encoder(), json.JSONEncoder)
Out[2]: True
Note also that unlike some of the implementations suggested in other answers we only create instances of the sub-encoders once, exactly when we create an instance of the parent MultipleJsonEncoders
class.
Theres a small amount of additional work you could do to polish things up- for example the str representation of the returned class is pretty messy and could use a __str__
or __repr__
implementation.