Access elements of an anonymous array via JsonPath in RestAssured
Asked Answered
L

2

33

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.

Lizzielizzy answered 10/12, 2012 at 14:51 Comment(0)
U
46

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.

Ursine answered 11/12, 2012 at 12:12 Comment(1)
I know it is not valid - that is why I wrote "pseudocode" in the first line of my question :-)Lizzielizzy
W
33

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));
Wie answered 1/11, 2014 at 21:27 Comment(4)
Just be careful with this - the order of elements may not always be the same.Housecoat
That's right, that's the main reason for using "hasItems" in the first place - you use it in cases where you can't expect a specific (and fixed) order.Madea
This is correct but if order gets change, it will surely fail.Bluegrass
maybe Hamcrest containsInAnyOrder() will help you... hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/…Topazolite

© 2022 - 2024 — McMap. All rights reserved.