Access elements of an anonymous array via JsonPath in RestAssured

Heiko Rupp picture Heiko Rupp · Dec 10, 2012 · Viewed 21.8k times · Source

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.

Answer

Johan picture Johan · Dec 11, 2012

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.