Parse the JSON response body using JsonPath class in REST Assured

Profile picture for user devraj
Submitted by devraj on

JsonPath is an alternative to using XPath for easily getting values from a Object document. It follows the Groovy GPath syntax when getting an object from the document. You can regard it as an alternative to XPath for JSON.

Consider Below Example:

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import static org.hamcrest.Matchers.*;
import static io.restassured.RestAssured.given;

public class ReqRes 
    public void setup()
        RestAssured.baseURI = "";
        RestAssured.basePath = "api";
    public void postRequestExample()
        String res = 
            .body("{" + 
                "    \"name\": \"Tarun\",\n" + 
                "    \"job\": \"Goswami\"\n" + 
        JsonPath js = new JsonPath(res);
        String id = js.getString("id");
        System.out.println("id is:"+id);

In above code we got the id using JsonPath object and method getString. This case is useful when you want to re use this id further in your program.