/ Published in: Python
Makes working with JSON data, in my eyes, easier in Python.
Instead of
json_data['key']['key']['key']
Do
json_data.key.key.key
This can also be modified to work the same way with dict types.
Instead of
json_data['key']['key']['key']
Do
json_data.key.key.key
This can also be modified to work the same way with dict types.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
import json class objectjson: def __init__(self, json_data): if isinstance(json_data, basestring): json_data = json.loads(json_data) self.json_data = json_data def __getattr__(self, key): if key in self.json_data: if isinstance(self.json_data[key], (list, dict)): return objectjson(self.json_data[key]) else: return self.json_data[key] else: raise Exception('There is no json_data[\'{key}\'].'.format(key=key)) def __repr__(self): out = self.__dict__ return '%r' % (out['json_data']) j = objectjson('{"test":{"a":1,"b":2,"c":3}}') print(j, j.test, j.test.a)