Make the Python json encoder support Python's new dataclasses

前端 未结 6 1326
忘掉有多难
忘掉有多难 2021-02-03 16:59

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

from dataclasses import dataclass

@dataclass
class Foo:
    x: str

However, t

6条回答
  •  半阙折子戏
    2021-02-03 17:53

    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)
    

提交回复
热议问题