Search code examples
jsonrest-assuredrest-assured-jsonpath

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.


Solution

  • 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.