4

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.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Animesh Pandey
  • 5,900
  • 13
  • 64
  • 130

3 Answers3

7

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__() .

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
1

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.

viraptor
  • 33,322
  • 10
  • 107
  • 191
0

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.

Community
  • 1
  • 1
maxymoo
  • 35,286
  • 11
  • 92
  • 119