【问题标题】:How to read JSON (in mentioned format)?如何读取 JSON(以上述格式)?
【发布时间】:2019-01-08 08:12:04
【问题描述】:

我必须从下面的 JSON 响应中单独解析并获取 'id' 字段值(即在本例中为 13)。我的 JSON 响应将采用以下格式。这是获取政策 nessus 电话

{'policies': [{'creation_date': 1546583582,
               'description': 'New Scan',
               'has_credentials': 0,
               'id': 13}]}

我的代码:

import requests
from first import *
url = 'https://localhost:8834/policies'
headers = {'X-Cookie':mys()}
response = requests.get(url, headers=headers, verify=False)
resp = response.json()
for k,v in resp.items():
    print (v)

代码响应:

[{'creation_date': 1546583582,'description': 'New Scan','has_credentials': 0,'id': 13}]

我不确定如何编写代码以得到预期的结果响应 - 'id' : 13 或只是 13

【问题讨论】:

  • 假设你调用了列表末尾的a。那么它将是a[0][‘id’]
  • @JackMoody:兄弟!我得到整个文件([{'creation_date': 1546583582,'description': 'New Scan','has_credentials': 0,'id': 13}]) 作为 response = requests.get(url, headers= headers, verify=False) 但我需要知道如何单独打印 'id'=13 值?
  • 我认为@JackMoody 的意思是,就您的代码而言,使用print(v[0]['id'])

标签: python json python-3.x nessus


【解决方案1】:

您可以通过以下任何一种方式进行操作:

resp = {'policies': [{'creation_date': 1546583582,
                      'description': 'New Scan',
                      'has_credentials': 0,
                      'id': 13}]}

for k,v in resp.items():
    print(v[0]['id'])  # -> 13

# or

print(resp.popitem()[1][0]['id'])  # -> 13

【讨论】:

    【解决方案2】:

    如果您有多个策略并且想要提取 id 到列表中,您可以使用列表解析,例如 [policy.get('id') for policies in resp.values() for policy in policies] 这样你就会得到一个 id 列表

    另一种选择是循环:

    for policies in resp.values(): for policy in policies: print(policy.get('id'))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-10
      • 2021-01-14
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 2020-10-31
      相关资源
      最近更新 更多