Search code examples
javajsonrest-assuredjsonpathrest-assured-jsonpath

What is the Rest Assured proper JsonPath get() format for selecting the value of a field within an array of JSON objects


I am using rest assured to make an API post call and getting a response back in the body. I then need to take this response and select specific field values and store them as strings to be compared later against other string objects. I wrote jsonpath just fine to get the top level field values (like id, status, type, country, etc.) but when i have to get inside one of the objects within the json array that is returned I cant get the format correctly for the get() method.

Here is an example of the Json that is returned:

{
  "id": "ABC123",
  "status": "NEW",
  "type": "PERSONAL",
  "country": "United States",
  "totalBalances": {},
  "availableBalances": {},
  "fields": [
    {
      "fieldType": "mobilephone",
      "value": "14216904425",
      "fieldId": "personalMobileNumber"
    },
    {
      "fieldType": "email",
      "value": "user12345@work.com",
      "fieldId": "personalEmail"
    },
    {
      "fieldType": "STRING",
      "value": "John Doe",
      "fieldId": "individualName"
    }
  ]
}

Here is the json path I was trying to get formatted to fit into the get() method but i get an Illegal Argument exception everytime (java.lang.IllegalArgumentException: Invalid JSON expression) i try to make it work. Basically I need to identify the right object in the array and grab the proper field value. In this case that is the fieldId field and i want the field "value" value (John Doe) so that I can save that to a String object:

JsonPath pathToAccountName = response.jsonPath();
String accountName = pathToAccountName.get("fields[?(@.fieldId=='individualName')].value")

I used https://jsonpath.curiousconcept.com/ for the getting the VALID json path:

$.fields[?(@.fieldId=='individualName')].value

But I tried everything to convert it into something the get() method will accept and no luck. Scouring all the the posts here and the rest assured technical docs hasnt helped either.


Solution

  • Rest Assured uses Groovy's Gpath. So your query could look like this:

    JsonPath pathToAccountName = response.jsonPath();
    String value = jsonPath.getString("fields.find { it.fieldId == 'individualName' }.value");
    

    Here you can find some examples (it's about processing XML, but also applicable to JSON): http://groovy-lang.org/processing-xml.html