Objectjson - JSON to nested object.


/ Published in: Python
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. import json
  2.  
  3. class objectjson:
  4.  
  5. def __init__(self, json_data):
  6. if isinstance(json_data, basestring):
  7. json_data = json.loads(json_data)
  8. self.json_data = json_data
  9.  
  10. def __getattr__(self, key):
  11. if key in self.json_data:
  12. if isinstance(self.json_data[key], (list, dict)):
  13. return objectjson(self.json_data[key])
  14. else:
  15. return self.json_data[key]
  16. else:
  17. raise Exception('There is no json_data[\'{key}\'].'.format(key=key))
  18.  
  19. def __repr__(self):
  20. out = self.__dict__
  21. return '%r' % (out['json_data'])
  22.  
  23. j = objectjson('{"test":{"a":1,"b":2,"c":3}}')
  24. print(j, j.test, j.test.a)

URL: http://ideone.com/O6KGB3

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.