JsonPath:根据一级子元素获取根元素

JsonPath: get root element depending on first level sub-element

我需要下面 json 示例的所有元素(包括“id”和所有属性),其中“type”的值为“state_machine_state”,但前提是“type”已打开第一级。我不想要结果中的中间元素“order_transaction”,尽管它在第二层级中具有“type”:“state_machine_state”。

[
  {
    "id": "f45aa035eb424d26a0529d25b3647c32",
    "type": "state_machine_state",
    "attributes": {
      "technicalName": "cancelled",
      "name": "Cancelled",
      "stateMachineId": "7553ad2630044fa589d786135d5000ad",
      "customFields": null,
      "createdAt": "2020-06-05T14:23:30.503+02:00",
      "updatedAt": null,
      "translated": {
        "name": "Cancelled",
        "customFields": []
      },
      "apiAlias": null
    }
  },
  {
    "id": "2d24ed4179824dbe92eee2f3d4f885b1",
    "type": "order_transaction",
    "relationships": {
      "stateMachineState": {
        "data": {
          "type": "state_machine_state",
          "id": "21f236e8955f45d3931fc9e44615088a"
        }
      }
    },
    "meta": null
  },
  {
    "id": "d08e73da41b0473d83ea378a57a2fa1f",
    "type": "state_machine_state",
    "attributes": {
      "technicalName": "completed",
      "name": "Completed",
      "stateMachineId": "7553ad2630044fa589d786135d5000ad",
      "customFields": null,
      "createdAt": "2020-06-05T14:23:30.482+02:00",
      "updatedAt": null,
      "translated": {
        "name": "Completed",
        "customFields": []
      },
      "apiAlias": null
    },
    "meta": null
  }
]

通过下面的查询,我得到了所有三个元素

$..[?(@.type == 'state_machine_state')]

我只是无法 select 只有第一级元素。

有人可以帮忙吗?

一些实现将允许您 select 多个项目,但您将无法通过 它们的键获得值

例如,如果您这样做

$..[?(@.type == 'state_machine_state')['id','attributes']

您只会得到一个包含所有 id 值和所有 attributes 值的结果集。

[
  "f45aa035eb424d26a0529d25b3647c32",
  {
    "technicalName": "cancelled",
    "name": "Cancelled",
    "stateMachineId": "7553ad2630044fa589d786135d5000ad",
    "customFields": null,
    "createdAt": "2020-06-05T14:23:30.503+02:00",
    "updatedAt": null,
    "translated": {
      "name": "Cancelled",
      "customFields": []
    },
    "apiAlias": null
  },
  "2d24ed4179824dbe92eee2f3d4f885b1",
  "d08e73da41b0473d83ea378a57a2fa1f",
  {
    "technicalName": "completed",
    "name": "Completed",
    "stateMachineId": "7553ad2630044fa589d786135d5000ad",
    "customFields": null,
    "createdAt": "2020-06-05T14:23:30.482+02:00",
    "updatedAt": null,
    "translated": {
      "name": "Completed",
      "customFields": []
    },
    "apiAlias": null
  }
]

JSON 路径不是为转换而设计的。 JMES Path 可能能够满足您的需求,但我对它不太熟悉。

有时退后一步,换一种方式思考会有所帮助。 通过这个查询,我得到了我想要的:

$..[?(@.type == 'state_machine_state' && @.attributes)]

我需要的元素有属性,其他元素没有,所以我只是在过滤器中检查。