Open yjouyang opened 3 years ago
Hi @yjouyang. You can use key_transformer
for this.
Let's say you have:
>>> @dataclass
... class AClass:
... type_: str
...
>>> a = AClass("test")
A "normal" dump would get:
>>> jsons.dump(a)
{'type_': 'test'}
But in your case, you want:
>>> dumped = jsons.dump(a, key_transformer=lambda k: "type" if k == "type_" else k)
>>> dumped
{'type': 'test'}
The same goes for deserializing:
>>> loaded = jsons.load(dumped, AClass, key_transformer=lambda k: "type_" if k == "type" else k)
>>> loaded
AClass(type_='test')
Is there an easy way to support a custom key name? For example, the json is:
and I want to name the variable in python code to
type_
:since
type
is a built-in keyword in python and I don't want to use it.