通过在Python中使用JsonPath_ng检查特定条件来检索值

2024-05-06 16:39:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建示例JSON,如下所示。我想在一定条件下通过使用来检索值

请遵守以下语句行:

'$.Attributes..Attribute[?(@.setcode=="x")]'

但我无法使用代码检索该值

"{
  "Attributes": [
    {
      "Attribute": {
        "setcode": "x",
        "codeType": "movieType",
        "AttributeGroup": [
          {
            "code": "Force",
            "codeValueValue": "'I'"
          },
          {
            "code": "Remain",
            "codeValueValue": "'P'"
          },
          {
            "code": "Died",
            "codeValueValue": "'E'"
          },
          {
            "code": "Renew",
            "codeValueValue": "'R'"
          }
        ]
      }
      
    },
    {
      "Attribute":{
        "setcode": "y",
        "codeType": "movietype",
        "AttributeGroup": [
          {
            "code": "Force",
            "codeValueValue": "'I'"
          },
          {
            "code": "Remain",
            "codeValueValue": "'P'"
          },
          {
            "code": "Died",
            "codeValueValue": "'E'"
          },
          {
            "code": "Renew",
            "codeValueValue": "'R'"
          }
        ]
      }
    }
  ]
}"

Tags: json示例codeattribute语句条件attributesforce
1条回答
网友
1楼 · 发布于 2024-05-06 16:39:05

虽然您的path使用Java中的公共实现(Jayway)返回某些内容,但我可以确认,在jsonpath ng中使用它不会返回任何结果。问题是"filter op can only be used on lists",看起来需要在路径中预先从iterable开始:

我们必须在Attributes-数组上进行筛选,然后取而代之的是Attribute

$.Attributes[?(@.Attribute.setcode=="x")].Attribute

完整代码示例:

import json
json_string = """{
  "Attributes": [
    {
      "Attribute": {
        "setcode": "x",
        "codeType": "movieType",
        "AttributeGroup": [
          {
            "code": "Force",
            "codeValueValue": "'I'"
          },
          {
            "code": "Remain",
            "codeValueValue": "'P'"
          },
          {
            "code": "Died",
            "codeValueValue": "'E'"
          },
          {
            "code": "Renew",
            "codeValueValue": "'R'"
          }
        ]
      }          
    },
    {
      "Attribute":{
        "setcode": "y",
        "codeType": "movietype",
        "AttributeGroup": [
          {
            "code": "Force",
            "codeValueValue": "'I'"
          },
          {
            "code": "Remain",
            "codeValueValue": "'P'"
          },
          {
            "code": "Died",
            "codeValueValue": "'E'"
          },
          {
            "code": "Renew",
            "codeValueValue": "'R'"
          }
        ]
      }
    }
  ]
}"""

json_data = json.loads(json_string)

from jsonpath_ng.ext import parser
query = [x.value for x in parser.parse('$.Attributes[?(@.Attribute.setcode=="x")].Attribute').find(json_data)]
print(json.dumps(query))

相关问题 更多 >