1

Say you've got multiple encoders, like this:

class JsonDataClassEncoder(json.JSONEncoder):
    """
    Supports dataclasses
    """
    def default(self, o):
        if dataclasses.is_dataclass(o):
            return dataclasses.asdict(o)
        return super().default(o)


class JsonEnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Enum):
            return obj.name
        return super().default(obj)

Is there a way to combine them, without subclassing them, such that it would be possible to use

json.dumps(opj, cls=MultipleJsonEncoders(JsonEnumEncoder, JsonDataClassEncoder))

5 Answers 5

2
class MultipleJsonEncoders():
    """
    Combine multiple JSON encoders
    """
    def __init__(self, *encoders):
        self.encoders = encoders
        self.args = ()
        self.kwargs = {}

    def default(self, obj):
        for encoder in self.encoders:
            try:
                return encoder(*self.args, **self.kwargs).default(obj)
            except TypeError:
                pass
        raise TypeError(f'Object of type {obj.__class__.__name__} is not JSON serializable')

    def __call__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        enc = json.JSONEncoder(*args, **kwargs)
        enc.default = self.default
        return enc

Usage

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):
            return o.name
        return super().default(o)

class Enumm(enum.Enum):
    X = enum.auto()

obj = {'time': datetime.datetime.now(), 'enum': Enumm.X}
encoder = MultipleJsonEncoders(JsonDateEncoder, JsonEnumEncoder)

In [502]: json.dumps(obj, cls=encoder)
Out[502]: '{"time": "2020-12-23T08:51:43.646022", "enum": "X"}'

2
  • To the point! (and works like a charm) Maybe helpful if you provide a little more textual (background) information ..... e.g. why do you need the call ? Apr 20, 2022 at 15:28
  • MultipleJsonEncoders should inherit from JSONEncoder. I think to do so you just need to add a super() call to the __init__ and you can get rid of the __call__ entirely
    – avigil
    Aug 18 at 16:18
0

@tsorn's answer is great, I adapted it to strict type hinting as follows:

from json import JSONEncoder
from typing import Any, Type

class CombinedEncoder():
    """
    Combine multiple JSON encoders
    https://stackoverflow.com/questions/65338261/combine-multiple-json-encoders
    """
    def __new__(cls, *encoders: Type[JSONEncoder]):
        def default(o: Any, *args: bool, **kwargs: bool) -> str | Any:
            for encoder in encoders:
                try:
                    return encoder(*args, **kwargs).default(o)
                except TypeError:
                    pass
            raise TypeError(
                f'Object of type {o.__class__.__name__} is not JSON serializable')

        encoder = type(
            "CombinedEncoder",
            (JSONEncoder,),
            {
                "default": default,
                "__doc__": "Combines JSONEncoders"
            }
        )
        return encoder
1
  • This works well for situations where proper typing is necessary, but I think __new__ tends to be a bit harder to understand and use properly, I suggest an alternative approach using the factory pattern here
    – avigil
    Aug 18 at 17:51
0

You can also use a more functional approach: most json dump/load functions support the default argument. A look into the docs of the original source code reveals how to use it:

>>> import json
>>> def encode_complex(obj):
...     if isinstance(obj, complex):
...         return [obj.real, obj.imag]
...     raise TypeError(f'Object of type {obj.__class__.__name__} '
...                     f'is not JSON serializable')
...
>>> json.dumps(2 + 1j, default=encode_complex)
'[2.0, 1.0]'
>>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
'[2.0, 1.0]'
>>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
'[2.0, 1.0]'

This allows it to use simple functions instead of subclassing everything. Now you can combine encoders via a higher-order function.

def combine_encoders(*encs):
    def combined(obj):
        for enc in encs:
            try:
                return enc(obj)
            except TypeError:
                pass
        raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")

    return combined

combined_encoders = combine_encoders(encode_complex, encode_path)
encoded = json.dumps(data, default=combined_encoders)

For me the result looks a bit simpler, because you don't need to understand why a def __call__ definition is needed in the class-based approach.

0

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.

-1

Nothing. I have pursued code, but the module is not made to be accept multiple classes. If it can, how it decide order of encoders? You must use subclassing.

1
  • how it decide order of encoders by the order they are passed to MultipleJsonEncoders
    – tsorn
    Dec 17, 2020 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.