【问题标题】:Converting a nested dict to Python object将嵌套字典转换为 Python 对象
【发布时间】:2015-07-27 01:46:08
【问题描述】:

我有这个从 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

【问题讨论】:

  • 您想这样做的原因是什么?为什么不只是response_body['sub']['cn']
  • @MattDMo 数据已经在 python dict 中了。这个问题其实和json本身没什么太大关系,只是嵌套字典而已。
  • @viraptor 好吧,我正在尝试一些替代方案。
  • @viraptor 你说得对,我是在听他的话。来晚了……
  • @MattDMo 我也改变了它。我希望它现在很好。

标签: python json dictionary


【解决方案1】:

也许是这样的递归方法 -

>>> 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__() 中。

【讨论】:

    【解决方案2】:

    您可以使用response.items() 遍历所有键/值对,对于isinstance(value, dict) 的每个值,将其替换为sample_token(**value)

    没有什么会自动为您执行递归。

    【讨论】:

      【解决方案3】:

      一旦您在 Python 中评估了表达式,它就不再是 JSON 对象了;这是一个 Python dict;访问条目的常用方法是使用 [] 索引器表示法,例如:

      response_body['sub']['uid']
      'gandalf'
      

      如果您必须将其作为对象而不是字典访问,请查看问题Convert Python dict to object? 中的答案;嵌套 dicts 的情况包含在后面的答案之一中。

      【讨论】:

        猜你喜欢
        • 2019-10-10
        • 2020-05-16
        • 2021-09-25
        • 1970-01-01
        • 1970-01-01
        • 2022-06-14
        • 2023-03-11
        • 1970-01-01
        • 2019-12-26
        相关资源
        最近更新 更多