【问题标题】:Is there a way to filter JSON data with Python有没有办法用 Python 过滤 JSON 数据
【发布时间】:2019-05-07 18:38:10
【问题描述】:

我正在使用 PRTG HTTP API 来提取传感器信息,我的目标是过滤出具有此值的传感器

<status>Down</status>

到目前为止,我已经阅读了 Stack 和 Google 搜索中的很多参考资料,但我无法应用这些解决方案,因此粘贴我尝试过的所有代码都是徒劳的,但是更有意义的代码我就是这个

JSON的结构是这样的

{
  "prtg-version": "19.1.49.1966",
  "treesize": 17701,
  "status%3Ddown": [
    {
      "group": "SOME GROUP",
      "device": "SOME SWITCH",
      "sensor": "Uptime",
      "status": "Down",
      "status_raw": 5
    },
    {
      "group": "SOME GROUP",
      "device": "SOME SWITCH",
      "sensor": "System Health Memory",
      "status": "Up",
      "status_raw": 3
    },
  ]
}

现在是代码

import json
import requests
url = "https://prtg.c3ntro.com/api/table.jsoncontent=status=down&username=usr&passhash=hash&count=100"
response = requests.get(url)
data = response.json()

d = data
result_dict = [d for d in data['status%3Ddown'] if d['status'] == 'Down']
print(result_dict)


#Code has been fixed and now it works

现在只打印 Down 状态传感器

【问题讨论】:

  • 你希望data["prtg-version", "treesize", "status%3Ddown"] 做什么?
  • 对不起,我猜我粘贴了错误的代码,我实际上是在使用 ata["device", "status", "status%3Ddown"] 字典,但我得到了它与 "davedwards" 答案一起使用谢谢大家的代码是固定的

标签: python json numpy dictionary prtg


【解决方案1】:

列表推导应该可以工作:

[d for d in data['status%3Ddown'] if d['status'] == 'Down']

返回"status%3Ddown"列表中包含"status": "Down"的所有条目:

[{'device': 'SOME SWITCH',
  'group': 'SOME GROUP',
  'sensor': 'Uptime',
  'status': 'Down',
  'status_raw': 5}]

【讨论】:

  • 非常感谢戴夫,它现在可以工作了,问题中的代码已被修复,只是为了展示它是如何修复的(:
【解决方案2】:
d = data["prtg-version", "treesize", "status%3Ddown"]

那行代码试图使用文字三部分键"prtg-version", "treesize", "status%3Ddown" 访问一个元素,这当然不存在。

看起来你只是想要这个:

d = data["status%3Ddown"]

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    相关资源
    最近更新 更多