Closed tlzAny closed 4 years ago
update: Like this I can skip the attribute which works for the moment but an alias would be still a good feature.
obj: NetworkPolicyObject = jsons.loads(
content, cls=NetworkPolicyObject, strict=False, strip_attr="type"
)
``
Hi @tlzAny ,
You can use key_transformer
for that. It takes a callable that accepts a string (the attribute name) and expects a 'transformed' key as return value.
Example:
>>> from dataclasses import dataclass
>>> import jsons
>>> d={'type': 1}
>>> @dataclass
... class C:
... type_: int
...
>>> jsons.load(d, cls=C, key_transformer=lambda key: 'type_' if key == 'type' else key)
C(type_=1)
hi ramonhagenaars Thank you for your fast reply. That's good to know.
Hi I searched for a very long time a python library that has released version and can handle deserialization from json to object by given dataclass. Now for my usecase I got a json file input with a python keyword 'type' in its body. I look for some annotation to make an alias for an attribute with different nyme i.e. _type instead of type. See similiar question here: https://stackoverflow.com/questions/60074344/reserved-word-as-an-attribute-name-in-a-dataclass-when-parsing-a-json-object
sample json entry
generated dataclass with json2python-models: r""" generated by json2python-models v0.2.1 at Tue Sep 8 06:54:48 2020 command: /home/xxx/workspace/test-python-123/.venv/bin/json2models -m NetWorkObjects sample_getnetworkobjects.json -f dataclasses """ from dataclasses import dataclass, field from typing import List, Literal, Optional, Union