by ig1 · 12y ago · 0 comments
https://github.com/imranghory/pson
(Also available from pypi via "pip install pson")
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']My longer term intention is adding other useful json manipulation and search functions to the library.
By the way, you should remove the pprint import from the library, since you don't use it :)
def rget(obj, attrstr, default=None, delim='.'):
try:
parts = attrstr.split(delim, 1)
attr = parts[0]
attrstr = parts[1] if len(parts) == 2 else None
if isinstance(obj, dict): value = obj[attr]
elif isinstance(obj, list): value = obj[int(attr)]
elif isinstance(obj, tuple): value = obj[int(attr)]
elif isinstance(obj, object): value = getattr(obj, attr)
if attrstr: return rget(value, attrstr, default, delim)
return value
except:
return default- jmespath uses `body.translations[0].language` instead of `body.translations.0.language`, and it can also do `body.translations[].language`.
- jmespath doesn't support the "missing" use case