Skip to content

Instantly share code, notes, and snippets.

@mrmurphy
Created September 18, 2012 15:37
Show Gist options
  • Save mrmurphy/3743805 to your computer and use it in GitHub Desktop.
Save mrmurphy/3743805 to your computer and use it in GitHub Desktop.
Read a JSON file from disk into a python object
import json
class Jsobject(dict):
marker = object()
def __init__(self, value=None, file=False):
if not value:
pass
if file:
f = open(value)
value = json.loads(f.read())
if isinstance(value, dict):
for key in value:
self.__setitem__(key, value[key])
else:
raise TypeError, 'Expected a dictionary.'
def __setitem__(self, key, value):
if (isinstance(value, list) and len(value) == 1 and
isinstance(value[0], dict)):
value = value[0]
if isinstance(value, dict) and not isinstance(value, Jsobject):
value = Jsobject(value)
dict.__setitem__(self, key, value)
def __getitem__(self, key):
found = self.get(key, Jsobject.marker)
if found is Jsobject.marker:
found = Jsobject()
dict.__setitem__(self, key, found)
return found
__setattr__ = __setitem__
__getattr__ = __getitem__
if __name__ == '__main__':
foo = Jsobject('foo.json', file=True)
print foo.keys()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment