3 ms·
class MyDict(object): def __init__(self, d): self.__dict__.extend(d) def __repr__(self): return repr(self.__dict__) import json r = jso
by icebraining 13y ago
class MyDict(object):
def __init__(self, d):
self.__dict__.extend(d)
def __repr__(self):
return repr(self.__dict__)
import json
r = json.loads('{"body": {"translations": [{"tr...', object_hook=MyDict)
>>> r.header.title
u'Hello World'
>>> r.body.translations[1]
{u'translation': u'guten tag', u'language': u'german'}
>>> map(attrgetter('language'), r.body.translations)
[u'french', u'german']
- ig1 13y agoThe code in the library is actually pretty simple, but deals with many practical edge-cases (stepping into an array, handling missing values gracefully, etc.) that the above code doesn't. My longer term intention is adding other useful json manipulation and search functions to the library.
- icebraining 13y agoYeah. I just don't like putting syntax in a string; I'd rather use Python itself. By the way, you should remove the pprint import from the library, since you don't use it :)
- ig1 13y agoI considered that approach but found the JSON returned by some third-party apis contained characters in keys (dashes, spaces, etc) which have special meanings in python so can't be used natively.