I have a dict that I want to convert in JSON using simplejson.
How can I ensure that all the keys of my dict are lowercase ?
{
"DISTANCE": 17.059918745802999,
"name": "Foo Bar",
"Restaurant": {
"name": "Foo Bar",
"full_address": {
"country": "France",
"street": "Foo Bar",
"zip_code": "68190",
"city": "UNGERSHEIM"
},
"phone": "+33.389624300",
"longitude": "7.3064454",
"latitude": "47.8769091",
"id": "538"
},
"price": "",
"composition": "",
"profils": {},
"type_menu": "",
"ID": ""
},
EDIT: Thanks all to had a look at my question, I am sorry I didn't explain in detailed why I wanted this. It was to patch the JSONEmitter
of django-piston
.
Here is my solution :
def lower_key(in_dict):
if type(in_dict) is dict:
out_dict = {}
for key, item in in_dict.items():
out_dict[key.lower()] = lower_key(item)
return out_dict
elif type(in_dict) is list:
return [lower_key(obj) for obj in in_dict]
else:
return in_dict
>>> d = {"your": "DATA", "FROM": "above"}
>>> dict((k.lower(), v) for k, v in d.iteritems())
{'from': 'above', 'your': 'DATA'}
>>> def lower_keys(x):
... if isinstance(x, list):
... return [lower_keys(v) for v in x]
... elif isinstance(x, dict):
... return dict((k.lower(), lower_keys(v)) for k, v in x.iteritems())
... else:
... return x
...
>>> lower_keys({"NESTED": {"ANSWER": 42}})
{'nested': {'answer': 42}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With