Ani*_*dey 2 python json dictionary
我有这个从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'
}
}
Run Code Online (Sandbox Code Playgroud)
我使用以下代码将其转换为Python对象:
class sample_token:
def __init__(self, **response):
self.__dict__.update(response)
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
s = sample_token(**response_body)
Run Code Online (Sandbox Code Playgroud)
在此之后,我可以通过访问值s.access_token
,s.name
等等。但是价值c.sub
也是一本字典。如何使用此技术获取嵌套字典的值?即s.sub.cn
返回Gandalf Grey
。
也许像这样的递归方法-
>>> 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'
Run Code Online (Sandbox Code Playgroud)
我们遍历key:value
响应中的每一对,如果value是一个字典,我们将为此创建一个sample_token对象,并将该新对象放入__dict__()
。