REST Assured JsonPath Iterate Array

Profile picture for user devraj

Iterating over JSON Array is same as you iterate using loops on other Array elements. There is nothing special you need to do. Check below example: 

For demo we will consider reqrest List Users api, here is the sample response:

{
    "page": 2,
    "per_page": 6,
    "total": 12,
    "total_pages": 2,
    "data": [
        {
            "id": 7,
            "email": "michael.lawson@reqres.in",
            "first_name": "Michael",
            "last_name": "Lawson",
            "avatar": "https://reqres.in/img/faces/7-image.jpg"
        },
        {
            "id": 8,
            "email": "lindsay.ferguson@reqres.in",
            "first_name": "Lindsay",
            "last_name": "Ferguson",
            "avatar": "https://reqres.in/img/faces/8-image.jpg"
        },
        {
            "id": 9,
            "email": "tobias.funke@reqres.in",
            "first_name": "Tobias",
            "last_name": "Funke",
            "avatar": "https://reqres.in/img/faces/9-image.jpg"
        }
}

JsonPath Loop through Array

Then we will read all the emails from response. 

public class ReqRes 
{
	public static String id = "2";
	
	@BeforeClass
	public void setup()
	{
		RestAssured.baseURI = "https://reqres.in/";
		RestAssured.basePath = "api";
	}
	
	
	@Test(enabled=true)
	public void IterateJSONArray()
	{
		Response res = given()
			.queryParam("page", "2")
		.when()
			.get("/users/");
			
		JsonPath js = new JsonPath(res.asString());
		
		int size = js.getInt("data.size()");
		System.out.println("size is: "+size);
		
		
		for(int i = 0; i < size; i++)
		{
			System.out.println(js.getString("data["+i+"].email"));			
		}
	}
}

In above example you can see we have pass the index of array inside getString method using String concatenation and print out the result.