python - 将嵌套字典转换为 Python 对象

标签 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'
    }
}

我使用以下方法将其转换为 Python 对象:

class sample_token:
    def __init__(self, **response):
        self.__dict__.update(response)

并像这样使用它:

s = sample_token(**response_body)

在此之后,我可以使用 s.access_tokens.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'

我们遍历响应中的每个 key:value 对,如果 value 是一个字典,我们为其创建一个 sample_token 对象并将该新对象放入 __dict__() .

关于python - 将嵌套字典转换为 Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31643861/

相关文章:

json - 我如何在 mvc 中返回 json 对象

c++ - 如何按值对 STL 映射进行排序?

python - FastAPI swaggerUI 显示嵌套路由两次

python - 属性错误: Unknown property cmap

python - 从 python 中的 {x,y,z}-散点数据绘制 3D 表面

python - matplotlib 中的自定义标记

javascript - 访问 $.ajax 语句内分配的 JSON 时出现问题

php - 在 laravel 中返​​回 json

ios - 从属性构建索引

python - 通过缩短键大小来优化 Python 字典查找速度?