JSONPath表达式:根据特定属性的存在或另一个属性的值获取其值

Kur*_*ews 4 json jsonpath

我有一个嵌套的父/子结构的JSON结构:

{
  "type": "site",
  "profile_id": "site profile id",
  "children": [
    {
      "type": "dealer",
      "profile_id": "dealer profile id",
      "children": [
        {
          "type": "location",
          "profile_id": "location profile id",
          "children": [
            {
              "type": "customer",
              "profile_id": "customer profile id",
              "children": [
                {
                  "type": "farm",
                  "farm_id": "farm id",
                  "children": [
                    {
                      "type": "field",
                      "field_id": "field id"
                     }]}]}]}]}]}
Run Code Online (Sandbox Code Playgroud)

JSONPath中有某种方法可以执行以下操作之一:

  1. 如果有profile_id,请给我;如果有farm_id,请给我;如果有,请给我field_id。

  2. 如果type = customer,请给我profile_id;如果type = farm,请给我farm_id;如果type = field,请给我field_id

  3. 给我每个班级的第n个属性。id实际上是每个类中的第三个属性。这是我最不喜欢的选项,因为我不知道id是否始终是第三个属性。

Dun*_*can 5

下面是需要3个单独查询的选项2的解决方案。这是3个查询:

$..[?(@.type=='customer')].profile_id
$..[?(@.type=='farm')].farm_id
$..[?(@.type=='field')].field_id
Run Code Online (Sandbox Code Playgroud)

我使用http://www.jsonquerytool.com验证了这些查询

另请参见此问题以获取类似示例。