【问题标题】:How do I get all the key/values if a specific key matches a query?如果特定键与查询匹配,我如何获取所有键/值?
【发布时间】:2018-10-29 15:06:29
【问题描述】:

在 python 中,我正在访问一个返回警报列表的 API,如下所示:

{
  "items": [
    {
      "AlertID": 0,
      "Code": 0,
      "Source": "string",
      "Title": "string",
      "Severity": "Information",
      "Created": "2018-10-29T14:57:05.639Z",
      "ThresholdValue1": "string",
      "ThresholdValue2": "string",
      "ThresholdValue3": "string",
      "ThresholdValue4": "string",
      "ThresholdValue5": "string",
      "SnoozedEndDate": "2018-10-29T14:57:05.639Z",
      "DeviceGuid": "string",
      "AdditionalInfo": "string",
      "Archived": true,
      "AlertCategoryID": "Hardware",
      "ArchivedDate": "2018-10-29T14:57:05.639Z",
      "TicketID": 0,
      "AlertMessage": "string",
      "DeviceName": "string",
      "CustomerID": 0,
      "CustomerName": "string",
      "MessageTemplate": "string",
      "FolderID": 0,
      "PollingCyclesCount": 0
    }
  ],
  "totalItemCount": 0,
  "page": 0,
  "itemsInPage": 0,
  "totalPages": 0,
  "prevLink": "string",
  "nextLink": "string"
}

这将返回一个包含 20 个警报的列表。如果我想打印键 'Archived' 的值为 'false' 的任何警报的所有详细信息,那么最好的方法是什么?我只需要查看有关当前警报的详细信息,而不是存档的警报。如果我也传入特定的 AlertID,API 也可以返回详细信息,这个特定的 url 为我提供了所有警报的列表。

【问题讨论】:

  • 返回的是字符串还是字典?
  • API返回一个json字符串,然后我使用json.loads将它序列化成一个dict。

标签: python json dictionary


【解决方案1】:
for alert in result['items']:
    if alert.get('Archived') is False:
        print(alert)

【讨论】:

  • 感谢您提供代码 sn-p,它可能会提供一些有限的即时帮助。通过描述为什么这是解决问题的好方法,正确的解释将极大地改进其long-term value,并使其对有其他类似问题的未来读者更有用。请编辑您的答案以添加一些解释,包括您所做的假设。
【解决方案2】:

你应该简单地,假设你有它作为一个 json 对象,能够

if json_var["items"]["archived"] == false:
    print <whatever info you want>

见:Parsing values from a JSON file?

【讨论】:

    【解决方案3】:

    试试这个?我不认为由于items 而导致的其他作品是包含一本字典的列表。

    print('\n'.join([e for e in result if not e['items'][0]['Archived']])
    

    【讨论】:

      【解决方案4】:

      这应该是一个简单的过滤器:

      alerts = api_response['items']
      
      live_alerts = [alert for alert in alerts if not alert['Archived']]
      

      这将为您提供 Archived 为 false 的所有项目主体的列表。您可以编写另一个函数来处理它们:

      def process_alert(alert):
          print(alert)
          if alert['Severity'] = 'really serious alert':
              email_support(alert)
      
      for alert in live_alerts:
          process_alert(alert)
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 2013-07-14
      相关资源
      最近更新 更多