python - 根据其他已知的 k/v 对从嵌套 json 中提取 k/v 对
问题描述
我确实收到了一个 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)基于“描述”的计数值:“运行作业”或(B)基于“描述”的JSON路径:“运行作业”所以我可以手动获取计数值.
我一直在研究JSONPath RW和其他一些选项,但是到目前为止,还没有找到明确的解决方案来以理智的方式做到这一点。
问题是,我无法更改源中的 JSON 以使其更容易,因为我不拥有 REST API 并且 JSON 文件可能相对较大,因此我正在寻找一种理智且执行此操作的方法。
解决方案
你可以试试 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'])
推荐阅读
- javascript - Javascript - 在新请求中使用来自先前请求的数据
- c# - 从 SharePoint 列表中检索所有项目并将每个字段放入一个对象中
- angular - Angular:具有外键数组的类
- xslt - xsl 想要将以下 xml 转换为 html:
- javascript - 如何在 vuetify 中动态添加/删除带有选择/自动完成值的新表单行?
- php - 如何在 PHP 中将变量连接成数组值?
- javascript - 使用对象从数组中删除重复项
- python - Python:如何有效地打开和读取来自多个进程的 zipfile
- javascript - 在js中,你能检测到页面什么时候没有焦点吗?
- wordpress - WordPress:如何禁用所有页面的页脚