Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access elements of an anonymous array via JsonPath in RestAssured

I have an anonymous array in JSON returned from a service like:

[
  {"foo":1, "bar":2 , "baz":3 },
  {"foo":3, "bar":4 , "baz":5 }
]

How can I access the bar elements e.g. in

expect().body("$[*].bar", hasItems(2,4)) 

I tried a few possibilities that I found here and also on the JsonPath page by Stefan Gössner, but whatever I try I get exceptions. My issue seems to directly come from trying to access that list of items.

like image 731
Heiko Rupp Avatar asked Dec 10 '12 14:12

Heiko Rupp


2 Answers

Given that you have:

[
  {"foo":1, "bar":2 , "baz":3 },
  {"foo":3, "bar":4 , "baz":5 }
]

You can do the following in Rest Assured:

then().body("bar",hasItems(2,4)) 

or

expect().body("bar",hasItems(2,4)) 

if you're using the legacy API.

like image 71
Johan Avatar answered Nov 12 '22 03:11

Johan


Johan's answer is correct, just for the sake of completeness: An alternative way to check the 'bar' elements with rest-assured would be

expect().
    body("[0].bar", equalTo(2)).
    body("[1].bar", equalTo(4));
like image 25
Matthias Avatar answered Nov 12 '22 01:11

Matthias