REST Assured - How can I determine if a JSON response path exists or doesn't exist?

Share This Post -
One of the most common problem: determine if a JSON response path exists or doesn't exist?

Solution:
Imagine that we have a resource called "/json" that returns the following JSON response:

{
   "done": true,
   "records": [
       {
           "Name": "Bob",
           "Phone": null,
           "CreatedDate": "2013-07-02T14:25:06Z",
           "Id": "0ca00000piscd1bj"
       }
   ],
   "size": 1
}

To verify that the records list contains the attribute Phone (even though it's null) we can do like this:

get("/json").then().assertThat().body("records.any { it.containsKey('Phone') }", is(true));

Likewise we can check that records doesn't contain an attribute called x:

get("/json").then().assertThat().body("records.any { it.containsKey('x') }", is(false));

To verify that a JSON object contains an element, for example to check that "size" is defined in the example above you can do like this:

get("/json").then().assertThat().body("any { it.key == 'size' }", is(true));