pythonpython-dataclasses

Make the Python json encoder support Python's new dataclasses


Starting with Python 3.7, there is something called a dataclass:

from dataclasses import dataclass

@dataclass
class Foo:
    x: str

However, the following fails:

>>> import json
>>> foo = Foo(x="bar")
>>> json.dumps(foo)
TypeError: Object of type Foo is not JSON serializable

How can I make json.dumps() encode instances of Foo into json objects?


Solution

  • Much like you can add support to the JSON encoder for datetime objects or Decimals, you can also provide a custom encoder subclass to serialize dataclasses:

    import dataclasses, json
    
    class EnhancedJSONEncoder(json.JSONEncoder):
            def default(self, o):
                if dataclasses.is_dataclass(o):
                    return dataclasses.asdict(o)
                return super().default(o)
    
    json.dumps(foo, cls=EnhancedJSONEncoder)