Closed dantebarba closed 3 years ago
It would be hard to come up with such behavior that makes sense, since Python itself is case-sensitive.
Python allows for the following, albeit pretty smelly:
@dataclass
class Category:
name: str = ""
Name: str = ""
nAme: str = ""
NaMe: str = ""
... # and so on
which attribute should be taken for the "name"
in your dict?
But here is what you can do: use the snake_case
key transformer:
@dataclass
class Category:
name: str = "" # <-- lower case (PEP-8 compliant)
id: str = ""
d = {"id" : "1234", "Name": "Car"} # <-- Uppercase "N" in "Name"
# This should do the trick:
loaded_obj = jsons.load(d, cls=Category, key_transformer=jsons.snake_case)
The above will work if the keys in your original dict are in PascalCase or in camelCase. If you have a non-standard casing, you could use a lookup dict, like so:
lookup = {
"Name": "name",
}
loaded_obj = jsons.load(d, cls=Category, key_transformer=lambda key: lookup.get(key, key))
Excellent
Thanks.
I'm currently using jsons with @dataclass and I was wondering if there is the possibility to map objects attributes in a case-insensitive way.
This would mean that
Should be able to be mapped with the jsons: