我确实收到了一个JSON文件,该文件可以在Python中进行大部分处理。但是,文件的一部分包含的数据结构如下例所示。
{
"panObjectAggregateResultList": [
{"rownumber": 1,"field": "detector","id": "331","description": "running jobs","count": 4,"quantile": null,"quantile_class": null},
{"rownumber": 2,"field": "detector","id": "51","description": "closed lines","count": 29,"quantile": null,"quantile_class": null},
{"rownumber": 3,"field": "detector","id": "334","description": "pids","count": 2,"quantile": null,"quantile_class": null}
]
}
作为一个例子,我需要获取“正在运行的作业”的值计数,但是,我在Python中通过文件搜索的唯一“值”是“正在运行的作业”。
我想要实现的是从(A)基于“ description”:“运行中的作业”的计数中获取值,或者(B)基于“ description”:“运行中的作业”的JSON路径,以便我可以获取该值手动计数。
我一直在研究JSONPath RW和其他一些选项,但是到目前为止,还没有找到明智的解决方案来做到这一点。
问题是,由于我不拥有REST API,因此我无法更改源中的JSON来简化此操作,并且JSON文件可能相对较大,因此我正在寻找理智的方法并执行此操作。
答案 0 :(得分:0)
您可以尝试jsonpath-ng pip install jsonpath-ng
。
from jsonpath_ng.ext import parse
null = None
json_data = {
"panObjectAggregateResultList": [
{"rownumber": 1,"field": "detector","id": "331","description": "running jobs","count": 4,"quantile": null,"quantile_class": null},
{"rownumber": 2,"field": "detector","id": "51","description": "closed lines","count": 29,"quantile": null,"quantile_class": null},
{"rownumber": 3,"field": "detector","id": "334","description": "pids","count": 2,"quantile": null,"quantile_class": null}
]
}
f = parse(f"$..panObjectAggregateResultList[?(@..description=='running jobs')]").find(json_data)
print(f[0].value['count'])