Reputation: 6018
I have this nested dictionary that I get from an API.
response_body = \
{
u'access_token':u'SIF_HMACSHA256lxWT0K',
u'expires_in':86000,
u'name':u'Gandalf Grey',
u'preferred_username':u'gandalf',
u'ref_id':u'ab1d4237-edd7-4edd-934f-3486eac5c262',
u'refresh_token':u'eyJhbGciOiJIUzI1N',
u'roles':u'Instructor',
u'sub':{
u'cn':u'Gandalf Grey',
u'dc':u'7477',
u'uid':u'gandalf',
u'uniqueIdentifier':u'ab1d4237-edd7-4edd-934f-3486eac5c262'
}
}
I used the following to convert it into a Python object:
class sample_token:
def __init__(self, **response):
self.__dict__.update(response)
and used it like this:
s = sample_token(**response_body)
After this, I can access the values using s.access_token
, s.name
etc. But the value of c.sub
is also a dictionary. How can I get the values of the nested dictionary using this technique? i.e. s.sub.cn
returns Gandalf Grey
.
Upvotes: 4
Views: 5090
Reputation: 90899
Maybe a recursive method like this -
>>> class sample_token:
... def __init__(self, **response):
... for k,v in response.items():
... if isinstance(v,dict):
... self.__dict__[k] = sample_token(**v)
... else:
... self.__dict__[k] = v
...
>>> s = sample_token(**response_body)
>>> s.sub
<__main__.sample_token object at 0x02CEA530>
>>> s.sub.cn
'Gandalf Grey'
We go over each key:value
pair in the response, and if value is a dictionary we create a sample_token object for that and put that new object in the __dict__()
.
Upvotes: 7
Reputation: 34145
You can iterate over all key/value pairs with response.items()
and for each value which isinstance(value, dict)
, replace it with sample_token(**value)
.
Nothing will do the recursion automagically for you.
Upvotes: 1
Reputation: 36545
Once you've evaluated the expression in Python, it's not a JSON object anymore; it's a Python dict
; the usual way to access entries is with the []
indexer notation, e.g.:
response_body['sub']['uid']
'gandalf'
If you must access it as an object rather than a dict, check out the answers in the question Convert Python dict to object?; the case of nested dicsts is covered in one of the later answers.
Upvotes: 0