Make the Python json encoder support Python's new dataclasses

前端 未结 6 1252
忘掉有多难
忘掉有多难 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:37

    If you are ok with using a library for that, you can use dataclasses-json. Here is an example:

    from dataclasses import dataclass
    
    from dataclasses_json import dataclass_json
    
    
    @dataclass_json
    @dataclass
    class Foo:
        x: str
    
    
    foo = Foo(x="some-string")
    foo_json = foo.to_json()
    

    It also supports embedded dataclasses - if your dataclass has a field typed as another dataclass - if all dataclasses envolved have the @dataclass_json decorator.

提交回复
热议问题