Search code examples
javajsonrest-assuredweb-api-testingrest-assured-jsonpath

extract value from json array of API response without brackets not working


Here is JSON:

{
"first":0,
"rows":100,
"data":[
{
"id":326,
"tag":"QATA9",
"workNo":"qat12345"
}
],
"totalRecords":1
}

And my code is :

JsonPath jsonPathEvaluator = response.jsonPath();
wID = jsonPathEvaluator.get("data.id");
System.out.println("id is "+ wID);

String responseBody = response.getBody().asString();
int statusCode = response.getStatusCode();

In output it shows [326] But i need value only 326


Solution

  • The [] delimits an array, so the library is treating it as an array. Just pick the first element, and you should be fine.

    Try this:

    JsonPath jsonPathEvaluator = response.jsonPath();
    wID = jsonPathEvaluator.get("data.id")[0];
    System.out.println("id is "+ wID);
    

    Then, again, you should also have in mind that, the fact that an array was used in the first place may indicate that you may have more than one element; in that case, you should simply loop through the array.