Search code examples
jsonapirest-assuredrest-assured-jsonpath

In restassurred, how to get particular attribute value using its sibling attribute value in json response of api?


Below is my response { "id": 123, "name": "text1" }, { "id": 456, "name": "text2" } ]

I want to find value of id whose name is 'text2'


Solution

  • Since Rest Assured uses Groovy's GPath you can use the following expression:

    String json = "[{ \"id\": 123, \"name\": \"text1\" }, { \"id\": 456, \"name\": \"text2\" }]";
    JsonPath path = JsonPath.from(json);
    System.out.println(path.get("find { it.name == 'text2' }.id"));
    

    The above code will return 456

    It will work only if the JSON starts with an array []