Make the Python json encoder support Python's new dataclasses

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

    Can't you just use the dataclasses.asdict() function to convert the dataclass to a dict? Something like:

    >>> @dataclass
    ... class Foo:
    ...     a: int
    ...     b: int
    ...     
    >>> x = Foo(1,2)
    >>> json.dumps(dataclasses.asdict(x))
    '{"a": 1, "b": 2}'
    

提交回复
热议问题