Open
Description
I have a use case in which a field in a JSON structure should be mapped into two separate fields in my dataclass:
{
"myJsonField": {
"first": "val1",
"second": "val2"
},
"otherField": "valotherfield"
}
I have tried using specialized decoders for each field, so I can extract the portion of what I need. In this case, I want to avoid creating another dataclass to decode the field "myJsonField":
contents = "{...}" # the JSON data above
def first_decoder(data: Dict[str, str]) -> str:
return data["first"]
def second_decoder(data: Dict[str, str]) -> str:
return data["second"]
@dataclass_json
@dataclass
class MyDataClass:
first: str = field(metadata=config(field_name="myJsonField", decoder=first_decoder))
second: str = field(metadata=config(field_name="myJsonField", decoder=second_decoder))
other_field: str = field(metadata=config(field_name="otherField"))
MyDataClass.from_json(contents)
The above does not work, as the second field overrides the first field.
What is the best way to tackle this case? Is there an alternative other than creating nested dataclasses?
Metadata
Metadata
Assignees
Labels
No labels