REST Assured Tutorial 58 – What is JsonPath and how to create it for simple and nested JSON Object?

Introduction

As a part of the End to End REST Assured Tutorial, in this post, we will learn about JsonPath.

If you are familiar with Xpath then you can understand JsonPath easily. The only difference is that XPath represents a path to reach a node in an XML document while JsonPath represents a path to reach a node in a JSON document.

Topics we are going to learn in this post

  1. What is JsonPath?
  2. How to write JsonPath for a simple JSON object?
  3. How to write JsonPath for a nested JSON object?

Prerequisite

As we are using RestAssured which includes JsonPath dependency by default, there is no need to include JsonPath dependency explicitly. I have used the below version of Rest Assured for this post:-



    io.rest-assured
    rest-assured
    4.3.3
    test

What is JsonPath?

JSON stands for “JavaScript Object Notation” which is a lightweight, language-independent, and self-describing format in-text for data storing and interchange. JSON is easy to read, write and create for humans which makes it famous over XML. To know more about JSON refer to my previous post – Introduction To JSON

A JSON consists of JSON Nodes or JSON elements. To traverse to a JSON element there will be a path. For example- Consider the below postal address:-

#404 , No More Apartment,
Gumnam Gali,
Bengaluru,
Karnataka, India

Actually, the above address shows a path to reach there. You need to go to India -> Karnataka -> Bengaluru -> Gumnma Gali -> No More apartment -> #404.

Similarly, a JsonPath represents a path to reach a JSON element and extract its value.

How to write JsonPath for a simple JSON object?

There are different syntaxes to write JsonPath but let’s start with a very simple JSON Object.

{
  "firstName": "Amod",
  "lastName": "Mahajan"
}

In the above JSON Object, we have two JSON elements or nodes “firstName” and “lastName” enclosed in two curly braces. To reach node “firstName” we need to start from the top curly brace. In fact, in any JSON object, there will be a root node which is represented as “$”(dollar). From this root node, we need to start to traverse through a JSON element.

Since there is a root node and “firstName” and “lastName” are children (direct) or child nodes of the root node. To reference a child node of a parent node we need to use the dot (.) symbol.

JsonPath for node “firstName” – $.firstName

JsonPath for node “lastName” – $.lastName

Whenever we write above JsonPath in RestAssured scripts, we don’t include dollar($) sign as it expects JsonPath has a root node.

To use JsonPath with RestAssured example, we need to get JsonPath instance of JSON Object, and then we can use respective methods to get the value of JSON element.

Example program

package JsonPathForJsonObject;

import io.restassured.path.json.JsonPath;

public class SimpleJsonObject {
	
	public static void main(String[] args) {
		
		String jsonString = "{\r\n" + 
				"  \"firstName\": \"Amod\",\r\n" + 
				"  \"lastName\": \"Mahajan\"\r\n" + 
				"}";
		
		//Get JsonPath instance of above JSON string
		JsonPath jsonPath = JsonPath.from(jsonString);
		
		// Since firstName holds a string value use getString() method and provide json path of firstName
		String firstName = jsonPath.getString("firstName");
		String lastName = jsonPath.getString("lastName");
		
		System.out.println("First name is : "+firstName);
		System.out.println("Last name is : "+lastName);
		
		// Since $ is root node of a JSON, we can get whole JSON string using $ as JSON path
		System.out.println(jsonPath.getString("$"));
		// There are two other ways to do the same thing as above
		System.out.println(jsonPath.getString(""));
		System.out.println(jsonPath.get());
		
	}

}
Output
First name is : Amod
Last name is : Mahajan
[firstName:Amod, lastName:Mahajan]
[firstName:Amod, lastName:Mahajan]
{firstName=Amod, lastName=Mahajan}

How to write JsonPath for a nested JSON object?

Let’s take the below example where I have nested JSON elements. JSON element “houseNo” is child node of “address”. JSON element “name” is a child node of “language” which is a child node of “skills”. This type of JSON object is called nested JSON object.

{
  "firstName": "Amod",
  "lastName": "Mahajan",
  "address": {
    "houseNo": 404,
    "buildingName": "Not Found",
    "streetName": "Gumnam gali",
    "city": "Bengaluru",
    "state": "Karnataka",
    "country": "India"
  },
  "skills": {
    "language": {
      "name": "Java",
      "proficiency": "Medium"
    }
  }
}

If we want to write JSON path for node “houseNo” then we need to traverse as below:-

root node ($) -> address -> houseNo

Since we represent a child of a parent using dot (.) the final JSONPath will be:-

$.address.houseNo

Similarly, for node “name”, JSON Path will be:-

$.skills.language.name

Example Program

package JsonPathForJsonObject;

import io.restassured.path.json.JsonPath;

public class NestedJsonObject {
	
	public static void main(String[] args) {
		
		String jsonString = "{\r\n" + 
				"  \"firstName\": \"Amod\",\r\n" + 
				"  \"lastName\": \"Mahajan\",\r\n" + 
				"  \"address\": {\r\n" + 
				"    \"houseNo\": 404,\r\n" + 
				"    \"buildingName\": \"Not Found\",\r\n" + 
				"    \"streetName\": \"Gumnam gali\",\r\n" + 
				"    \"city\": \"Bengaluru\",\r\n" + 
				"    \"state\": \"Karnataka\",\r\n" + 
				"    \"country\": \"India\"\r\n" + 
				"  },\r\n" + 
				"  \"skills\": {\r\n" + 
				"    \"language\": {\r\n" + 
				"      \"name\": \"Java\",\r\n" + 
				"      \"proficiency\": \"Medium\"\r\n" + 
				"    }\r\n" + 
				"  }\r\n" + 
				"}";
		
		//Get JsonPath instance of above JSON string
		JsonPath jsonPath = JsonPath.from(jsonString);
		
		// Since houseNo holds an int value use getInt() method and provide json path of houseNo
		int houseNo = jsonPath.getInt("address.houseNo");
		System.out.println("House no is : "+houseNo);
		
		String name = jsonPath.getString("skills.language.name");
		System.out.println("Name is : "+name);
		
	}

}
Output
House no is : 404
Name is : Java

You can download/clone the above sample project from here.

You can subscribe to my YouTube channel RetargetCommon to learn from video tutorials.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Many other topics you can navigate through the menu.

1 thought on “REST Assured Tutorial 58 – What is JsonPath and how to create it for simple and nested JSON Object?

  1. What would be the jsonpath for last count ?
    {
    “response”: {
    “homeworksSummary”: [
    {
    “count”: “0”,
    “title”: “Total Homework Created”,
    “icon”: “”,
    “type”: “total”,
    “lastModified”: “”
    },
    {
    “count”: “0”,
    “title”: “Published Homework”,
    “icon”: “”,
    “type”: “published”,
    “lastModified”: “”
    },
    {
    “count”: “2”,
    “title”: “Submited Homework”,
    “icon”: “”,
    “lastModified”: “2021-05-11 17:35:59”,
    “type”: “submitted”
    },
    {
    “count”: “46”,
    “title”: “Homework Saved as Draft”,
    “icon”: “”,
    “lastModified”: “2021-05-11 17:35:59”,
    “type”: “draft”
    }
    ]
    },
    “error”: null,
    “warning”: null
    }

Leave a Reply

Your email address will not be published. Required fields are marked *