Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the same field_name in more than one field #270

Open
eduardostarling opened this issue Dec 11, 2020 · 1 comment · May be fixed by #469
Open

Use the same field_name in more than one field #270

eduardostarling opened this issue Dec 11, 2020 · 1 comment · May be fixed by #469

Comments

@eduardostarling
Copy link

eduardostarling commented Dec 11, 2020

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?

@lavahot
Copy link

lavahot commented Oct 5, 2021

I ran into a similar problem. What I basically wound up realizing is that the structure of your dataclass has to mirror the structure of your serialized data. So you do have to make a nested dataclass. I wound up making variables like first and second here InitVar[str] and then wired them up to the nested dataclass in the __post_init__().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants