I am attempting to transform a "flat" JSON object to a more complex object using dataclasses and the library dataclasses-json. Unfortunately, I cannot change the JSON structure. An example of the JSON I am trying to decode, could be:
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"
}
Is there a nice way to encode/decode the JSON to/from a structure like this:
@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
Calling data.to_json()
should generate the same JSON output as above.