1

我正在尝试使用dataclasses和库dataclasses-json将“平面” JSON 对象转换为更复杂的对象。不幸的是,我无法更改 JSON 结构。我尝试解码的 JSON 示例可能是:

j = {
    "name": "hello",
    "added_at": "2020-01-01T12:00:00+00:00",
    "foo_item_pk": 1,
    "foo_item_name": "foo",
    "bar_item_pk: 2,
    "bar_item_name": "bar"
}

有没有一种很好的方法来编码/解码 JSON 到/从这样的结构:

@dataclass_json
@dataclass
class Item:
    pk: int
    name: str

@dataclass_json
@dataclass
class Data:
    pk: int
    added_at: added_at: datetime.datetime = field(
        metadata=config(
            encoder=datetime.datetime.isoformat,
            decoder=datetime.datetime.fromisoformat,
        )
    )
    foo: Item
    bar: Item

调用data.to_json()应生成与上述相同的 JSON 输出。

4

1 回答 1

0

您可以尝试使用 InitVar。

@dataclass_json
@dataclass
class Item:
    pk: int
    name: str

@dataclass_json
@dataclass
class Data:
    pk: int
    added_at: added_at: datetime.datetime = field(
        metadata=config(
            encoder=datetime.datetime.isoformat,
            decoder=datetime.datetime.fromisoformat,
        )
    )
    foo_item_pk: InitVar[int] = 0
    foo_item_name: InitVar[str] = ''
    foo: Item = field(default=None, init=False)

    def __post_init__(self, foo_item_pk, foo_item_name):
        self.foo = Item(foo_item_pk, foo_item_name)
于 2020-08-16T01:48:19.477 回答