Skip to content

Instantly share code, notes, and snippets.

@lsloan
Last active August 9, 2016 14:05
Show Gist options
  • Save lsloan/021633487010a47909dcace59f7e2963 to your computer and use it in GitHub Desktop.
Save lsloan/021633487010a47909dcace59f7e2963 to your computer and use it in GitHub Desktop.
Python: The solution I use to get objects from JSON.
from models import *
import json
def jsonObjectHook(self, jsonObject):
return SuperSimpleObject(**jsonObject)
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
x = json.loads(data, object_hook=jsonObjectHook)
assert x.name == 'John Smith'
assert x.hometown.name == 'New York'
from argparse import Namespace
class SuperSimpleObject(Namespace):
def __getattribute__(self, name):
"""
Unlike the default implementation, this method returns ``None``
rather than raise an ``AttributeError`` exception if an attribute
doesn't exist.
"""
attrValue = None
try:
attrValue = object.__getattribute__(self, name)
except AttributeError:
pass
return attrValue

Note: This code and documentation are incomplete.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment