I want to serialize and de-serialize some data with a dataclass, but one field in the received data has a different name than the class attribute I want to map it to for example in the data I have :
{"accountId":123,"shortKey": 54} and I want to map it to a dataclass like:
from dataclasses import dataclass
from dataclasses import field
@dataclass
class MySchema:
account_id=field(default=None, metadata=dict(required=False))
short_key=field(default=None, metadata=dict(required=False))
but I want to map between accountId<->account_id and shortKey<->short_key. How can this be done. I saw the data_key option but I read conflicting things whether this works for serilization and de-serialization. What is the way to do it
It is likely that libraries/frameworks for serialization, like "marshmallow" already do this.
However, it is just a matter of adding an extra function call on the pipeline to serialize/de-serialize stuff -
Say, we build a class which takes in the mapping rules and add a
to_pythonand afrom_pythonmethods:And then, this can be used either with
dataclasses.asdict, or as an outer call wrappingjson.dumpsorjson.loads. Also, I wrote it so "rules" can be a callable, and it would be easy to write a function to map all snake_case to CamelCase and use it with this class.(Note I needed the helper
list_sequencecall, because strings are "Sequences" but not ones we want apply these rules on all items)