0
{
  "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)]")
Santosh Hegde
  • 3,420
  • 10
  • 35
  • 51

1 Answers1

1

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);
}
gooamoko
  • 658
  • 12
  • 32