Extraction from JSON in Rest Assured

HOME

In this tutorial, I will explain how can we extract body from JSON Response in Rest Assured. This is needed for the assertion of tests. In t he previous tutorial, I have explained various types of Assertions can be done on JSON Request using Hamcrest.

JsonPath is available at the Central Maven Repository. Maven users add this to the POM.

<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
</dependency>

If the project is Gradle, add below dependency in build.gradle.

 testImplementation 'com.jayway.jsonpath:json-path:2.6.0'

JsonPath expressions can use the dot–notation.

$.store.book[0].title

or the bracket–notation

$['store']['book'][0]['title']

Below are the most commonly used expressions.

Expression Description
$ The root object or array.
.property Selects the specified property in a parent object.
[‘property’] Selects the specified property in a parent object. Be sure to put single quotes around the property name.Tip: Use this notation if the property name contains special characters such as spaces, or begins with a character other than A..Za..z_.
[n] Selects the n-th element from an array. Indexes are 0-based.
[index1,index2,…] Selects array elements with the specified indexes. Returns a list.
..property Recursive descent: Searches for the specified property name recursively and returns an array of all values with this property name. Always returns a list, even if just one property is found.
* Wildcard selects all elements in an object or an array, regardless of their names or indexes.
[start:end]
[start:]
Selects array elements from the start index and up to, but not including, end index. If end is omitted, selects all elements from start until the end of the array. Returns a list.
[:n] Selects the first n elements of the array. Returns a list.
[-n:] Selects the last n elements of the array. Returns a list.
[?(expression)] Selects all elements in an object or array that match the specified filter. Returns a list.
[(expression)] Script expressions can be used instead of explicit property names or indexes. An example is [(@.length-1)] which selects the last item in an array. Here, length refers to the length of the current array rather than a JSON field named length.
@ Used in filter expressions to refer to the current node being processed.

Below is the sample JSON which I am using for extraction examples.

String jsonString = {
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

To extract all books present in store:-

        String allBooks = JsonPath.read(jsonString, "$..*").toString();
		System.out.println("--------------- All books in the store --------------");
		System.out.println(allBooks);

Below are examples which shows how to extract different nodes from a JSON Body. I have used above JSON Body for these examples.

        // All bicycles in the store
		String allBicycles = JsonPath.read(jsonString, "$..bicycle").toString();
		System.out.println("--------------- All bicycles in the store ---------------");
		System.out.println(allBicycles);

		// The number of books
		String noOfBooks = JsonPath.read(jsonString, "$..book.length()").toString();
		System.out.println("--------------- The number of books ---------------");
		System.out.println(noOfBooks);

		// The authors of all books
		String authors = JsonPath.read(jsonString, "$.store.book[*].author").toString();
		System.out.println("--------------- Author of all Books ---------------");
		System.out.println(authors);

		// All authors
		String allAuthors = JsonPath.read(jsonString, "$..author").toString();
		System.out.println("--------------- All Authors ---------------");
		System.out.println(allAuthors);

		// All details of the store
		String store = JsonPath.read(jsonString, "$.store.*").toString();
		System.out.println("--------------- All details of the store ---------------");
		System.out.println(store);

		// Price of store
		String storePrice = JsonPath.read(jsonString, "$.store..price").toString();
		System.out.println("--------------- price of store ---------------");
		System.out.println(storePrice);

Below are the examples where I have extracted specific book (nodes) from the JSON body.

	    // Third book
		String thirdBook = JsonPath.read(jsonString, "$..book[2]").toString();
		System.out.println("--------------- third book ---------------");
		System.out.println(thirdBook);

		// first Last Book
		String firstLastBook = JsonPath.read(jsonString, "$..book[-1]").toString();
		System.out.println("--------------- first Last Book ---------------");
		System.out.println(firstLastBook);

		// first two Books
		String firstTwoBooks = JsonPath.read(jsonString, "$..book[0,1]").toString();
		System.out.println("--------------- first Two Books ---------------");
		System.out.println(firstTwoBooks);

		// books from index 0 (inclusive) until index 2 (exclusive)
		String booksRange = JsonPath.read(jsonString, "$..book[:2]").toString();
		System.out.println("--------------- books from index 0 (inclusive) until index 2 (exclusive) ---------------");
		System.out.println(booksRange);

		// All books from index 1 (inclusive) until index 2 (exclusive)
		String booksRange1 = JsonPath.read(jsonString, "$..book[1:2]").toString();
		System.out.println("------------ All books from index 1 (inclusive) until index 2 (exclusive) -----------");
		System.out.println(booksRange1);

		// Book number one from tail
		String bottomBook = JsonPath.read(jsonString, "$..book[1:]").toString();
		System.out.println("--------------- Book number one from tail ---------------");
		System.out.println(bottomBook);

Filters are logical expressions used to filter arrays. Below are the examples of a JSONPath expression with the filters.

       // All books in store expensive than 10
		String expensiveBook = JsonPath.read(jsonString, "$.store.book[?(@.price > 10)]").toString();
		System.out.println("--------------- All books in store costlier than 10 ---------------");
		System.out.println(expensiveBook);

		// All books in store that are not "expensive"
		String notExpensiveBook = JsonPath.read(jsonString, "$..book[?(@.price <= $['expensive'])]").toString();
		System.out.println("--------------- All books in store that are not expensive ---------------");
		System.out.println(notExpensiveBook);

		// All books in store that are equal to price 8.95
		String comparePrice = JsonPath.read(jsonString, "$.store.book[?(@.price == 8.95)]").toString();
		System.out.println("--------------- All books in store that are not expensive ---------------");
		System.out.println(comparePrice);

		// All books matching regex (ignore case)
		String regxExample = JsonPath.read(jsonString, "$..book[?(@.author =~ /.*REES/i)]").toString();
		System.out.println("--------------- All books matching regex (ignore case) ---------------");
		System.out.println(regxExample);

		// All books with price equal to mentioned list of prices
		String priceList = JsonPath.read(jsonString, "$..book[?(@.price in ['12.99', '8.99'])]").toString();
		System.out.println("--------------- All books with price equal to mentioned list of prices ---------------");
		System.out.println(priceList);

		// All books with price NOT equal to mentioned list of prices
		String excludePriceList = JsonPath.read(jsonString, "$..book[?(@.price nin ['12.99', '8.99'])]").toString();
		System.out.println("---------- All books with price NOT equal to mentioned list of prices ---------");
		System.out.println(excludePriceList);

		// All books with specified substring (case-sensitive)
		String substringExample = JsonPath.read(jsonString, "$..book[?(@.author contains 'Melville')]").toString();
		System.out.println("--------------- All books with specified substring (case-sensitive) ---------------");
		System.out.println(substringExample);

		// All books with an ISBN number
		String specificBook = JsonPath.read(jsonString, "$..book[?(@.isbn)]").toString();
		System.out.println("--------------- All books with an ISBN number ---------------");
		System.out.println(specificBook);

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s