简体   繁体   中英

Query for key with specific value from different objects of array in JSONPath

{
  "dataObject": [
    {
      "id": 263626,
      "role": {
        "id": 12054,
        "name": "Edit",
        "description": ""
      },
      "resource": {
        "id": 5756,
        "type": "resource"
      }
    },
    {
      "id": 263364,
      "role": {
        "id": 12054,
        "name": "Edit",
        "description": ""
      },
      "resource": {
        "id": 5728,
        "type": "resource"
      }
    }
  ]
}

I have a JSON object which looks like this. I need to extract the json object from dataObject which has name:Edit and id: 5756 . How can I achieve this using JSON path? Tried $..[?(@.name="Edit", @.id=5756)] which didn't work.

Java code:

JsonPath.parse(json).read("$..[?(@.name='Edit'), (@.id=5756)]")

Try to use parent object name and logical operator AND . The resulting path will be

$..[?((@.resource.id == 5756) && (@.role.name == 'Edit'))] .

It's work for me in unit test with com.jayway.jsonpath:json-path:2.4.0

@Test
public void testParse() {
    String json = "{\n" +
            "  \"dataObject\": [\n" +
            "    {\n" +
            "      \"id\": 263626,\n" +
            "      \"role\": {\n" +
            "        \"id\": 12054,\n" +
            "        \"name\": \"Edit\",\n" +
            "        \"description\": \"\"\n" +
            "      },\n" +
            "      \"resource\": {\n" +
            "        \"id\": 5756,\n" +
            "        \"type\": \"resource\"\n" +
            "      }\n" +
            "    },\n" +
            "    {\n" +
            "      \"id\": 263364,\n" +
            "      \"role\": {\n" +
            "        \"id\": 12054,\n" +
            "        \"name\": \"Edit\",\n" +
            "        \"description\": \"\"\n" +
            "      },\n" +
            "      \"resource\": {\n" +
            "        \"id\": 5728,\n" +
            "        \"type\": \"resource\"\n" +
            "      }\n" +
            "    }\n" +
            "  ]\n" +
            "}";

    DocumentContext parse = JsonPath.parse(json);
    Object read = parse.read("$..[?((@.resource.id == 5756) && (@.role.name == 'Edit'))]");
    assertNotNull(read);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM