1

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.

Kjell-Bear
  • 759
  • 1
  • 5
  • 12
  • 1
    You can probably roll your own class faster than trying to shoe-horn this into the dataclass object. – James May 28 '20 at 12:17

1 Answers1

0

You could try using 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)
Mateus Terra
  • 159
  • 1
  • 9