Return to Snippet

Revision: 63572
at May 17, 2013 23:23 by plainwreck


Initial Code
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)

Initial URL
http://ideone.com/O6KGB3

Initial Description
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.

Initial Title
Objectjson - JSON to nested object.

Initial Tags
python, json

Initial Language
Python