Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a nested dict to Python object

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.

like image 841
Animesh Pandey Avatar asked Feb 10 '23 11:02

Animesh Pandey


1 Answers

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

like image 60
Anand S Kumar Avatar answered Feb 12 '23 00:02

Anand S Kumar