【问题标题】:Accessing values from Rest API JSON output从 Rest API JSON 输出访问值
【发布时间】:2020-09-09 14:34:54
【问题描述】:

我正在尝试从返回的 REST API 输出中访问某些值。我已转换为字典,现在我正在尝试从“列表”开始访问列表中的元素:[

rest_response = {
                  "total": 2,
                  "offset": 0,
                  "limit": 25,
                  "list": [
                       {"id": 2233,
                        "url": "/v1/test/v2",
                        "enabled": true,
                        "info": {
                            "reason": "N/A",
                            "policy_name": "test",
                            "statuschk_tm": "2020-09-07 07:00:01",
                            "lock": "1",
                            "TYPE": "1"
                        }
                    ]
                 }

之前我已经能够编写一个 for 循环 a 来搜索列表中的值,如下所示。

rest_response = rest_response['list']
for info in rest_response:
    id = info['id']
    print(id)

但是,如果我使用类似的 for 循环来搜索在 "info": { 之后开始的值,则会出现关键错误。

rest_response = rest_response['info']
for info in rest_response:
    name = info['policy_name']
    print(name)

我查看过相关帖子,但是当我尝试访问时,我得到“TypeError:列表索引必须是整数或切片,而不是 str”

Python Accessing Nested JSON Data Having trouble with nested Python3 dictionary

关于我可以做些什么来查看“信息”中的值的任何想法:向前?

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    Info 本身就是一个字典,其中包含您无法直接访问的策略名称。所以你必须相应地嵌套。这应该有效:

    for x in rest_response:
        info = x['info']
        print(info['policy_name'])
    

    【讨论】:

      【解决方案2】:

      要访问信息字典,您必须使用以下代码 sn-p -

      rest_response['list'][0]['info']['policy_name']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-21
        • 2016-03-11
        • 2017-02-09
        • 1970-01-01
        • 1970-01-01
        • 2015-06-01
        • 2016-10-26
        • 2020-06-14
        相关资源
        最近更新 更多