首页 > 解决方案 > 根据其他已知的 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 文件可能相对较大,因此我正在寻找一种理智且执行此操作的方法。

标签: pythonjsonpath

解决方案


你可以试试 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'])

推荐阅读