Skip to content

Use the same field_name in more than one field #270

Open
@eduardostarling

Description

@eduardostarling

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions