ramonhagenaars / jsons

🐍 A Python lib for (de)serializing Python objects to/from JSON
https://jsons.readthedocs.io
MIT License
289 stars 41 forks source link

Custom key name? #129

Open yjouyang opened 3 years ago

yjouyang commented 3 years ago

Is there an easy way to support a custom key name? For example, the json is:

{"type":  "abc"}

and I want to name the variable in python code to type_:

@dataclass
class AClass:
    type_:  str

since type is a built-in keyword in python and I don't want to use it.

ramonhagenaars commented 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')