使用 JMESPath 按 JSON 中的部分字符串匹配进行过滤

Deb*_*bie 5 python json jmespath

下面是一个 JSON 示例:

{
  "School": [
  {"@id": "ABC_1",
  "SchoolType": {"@tc": "10023204",
   "#text": "BLUE FOX"}},
  {"@id": "ABC_2",
  "SchoolType": {"@tc": "143", "#text": "AN EAGLE"}},
  {"@id": "ABC_3",
  "SchoolType": {"@tc": "21474836", "#text": "OTHER REASONS"},
  "SchoolStatus": {"@tc": "21474836", "#text": "FINE"},
  "Teacher": [
    {"@id": "XYZ_1",
    "TeacherType": {"@tc": "5", "#text": "GENDER"},
    "Gender": "FEMALE",
    "Extension": {"@VC": "23",
     "Extension_Teacher": {"DateDuration": {"@tc": "10023111",
       "#text": "0-6 MONTHS"}}}},
    {"@id": "XYZ_2",
    "TeacherType": {"@tc": "23", "#text": "EDUCATED"},
    "Extension": {"@VC": "23",
     "Extension_Teacher": {"DateDuration": {"@tc": "10023111",
       "#text": "CURRENT"}}}}]},
  {"@id": "ABC_4",
  "SchoolType": {"@tc": "21474836", "#text": "OTHER DAYS"},
  "SchoolStatus": {"@tc": "1", "#text": "DOING OKAY"},
  "Extension": {"Extension_School": {"AdditionalDetails": "CHRISTMAS DAY"}}}]
}
Run Code Online (Sandbox Code Playgroud)

我想提取每个关联包含“OTHER”的Teacher信息(TeacherTypeGender)。Teacher @idSchoolType.\"#text\"School @idSchool

我尝试了以下查询,但它不起作用:

School[?SchoolType.\"#text\".contains(@, "OTHER")].Teacher[*].TeacherType.\"#text\"[]]
Run Code Online (Sandbox Code Playgroud)

β.ε*_*.βε 6

您必须以contains这种方式围绕条件数组扭曲函数:

[?contains(SchoolType."#text", 'OTHER')]
Run Code Online (Sandbox Code Playgroud)

因此,获取完整对象的方法Teacher是:

School[?contains(SchoolType."#text", 'OTHER')].Teacher
Run Code Online (Sandbox Code Playgroud)

或者,使用展平运算符摆脱数组的数组:

School[?contains(SchoolType."#text", 'OTHER')].Teacher | []
Run Code Online (Sandbox Code Playgroud)

这将给出:

[
  {
    "@id": "XYZ_1",
    "TeacherType": {
      "@tc": "5",
      "#text": "GENDER"
    },
    "Gender": "FEMALE",
    "Extension": {
      "@VC": "23",
      "Extension_Teacher": {
        "DateDuration": {
          "@tc": "10023111",
          "#text": "0-6 MONTHS"
        }
      }
    }
  },
  {
    "@id": "XYZ_2",
    "TeacherType": {
      "@tc": "23",
      "#text": "EDUCATED"
    },
    "Extension": {
      "@VC": "23",
      "Extension_Teacher": {
        "DateDuration": {
          "@tc": "10023111",
          "#text": "CURRENT"
        }
      }
    }
  }
]
Run Code Online (Sandbox Code Playgroud)