有没有一种方法可以使用Python过滤JSON数据

时间:2019-05-07 18:38:11

标签: python json numpy dictionary prtg

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

<status>Down</status>

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

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状态传感器

2 个答案:

答案 0 :(得分: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}]

答案 1 :(得分:0)

mxUnlock

该行代码试图使用文字的三部分键d = data["prtg-version", "treesize", "status%3Ddown"] 访问元素,该键当然不存在。

您似乎只想要这个:

"prtg-version", "treesize", "status%3Ddown"