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

Case-insensitive parsing is it possible? #142

Closed dantebarba closed 3 years ago

dantebarba commented 3 years ago

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

@dataclass
class Category:
   Name: str = ""
   id: str = ""

Should be able to be mapped with the jsons:

{ "id" : "1234", "Name": "Car"}
{ "id" : "1234", "name": "Car"}
ramonhagenaars commented 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))
dantebarba commented 3 years ago

Excellent

Thanks.