Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Need for JSON Comparison
3.
JSONassert Library 
4.
Compare JSON Objects Using the JSONassert Library in REST Assured
4.1.
Assertequals() Method
4.2.
Comparing JSON Object in LENIENT Mode
4.3.
Comparing JSON Object in STRICT Mode
4.4.
Handling Errors 
5.
Compare JSON Arrays Using the JSONassert Library in REST Assured
5.1.
Assertequals() Method
5.2.
Comparing JSON Arrays in LENIENT Mode
5.3.
Comparing JSON Arrays in STRICT Mode
6.
Frequently Asked Questions
6.1.
Are REST assured and REST API the same?
6.2.
Why is JSON used over XML?
6.3.
Which is better, postman or rest assured?
6.4.
What are {} and [] used in JSONpath expressions for?
6.5.
Is JSON secure or free from viruses?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

REST Assured - Compare JSON Objects and Arrays using JSONassert Library

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Hello ninjas,
We compare two things either when we want to know which one is better or to be sure if both of them are the same or not. A similar situation happens with JSON objects and arrays.

REST Assured  – Compare JSON Objects and arrays using JSONassert Library

This article will help you understand how to compare JSON objects using the JSONassert library. We will also learn how to compare JSON arrays using the JSONassert library in REST assured.

Need for JSON Comparison

Let’s learn some essential concepts first,

JSON objects contain key-value pairs. It is surrounded by curly brackets { }. 
It is written in “ Key: value “ format.

comparing JSON

Similar types of JSON objects are stored in JSON arrays.
It is represented by straight brackets [ ].

We need to compare JSON objects or JSON arrays using the JSONassert library in REST assured because:

  •  To check if data dependencies are relevant.
     
  •  To check if the JSON data format is correct or not.
     
  •  To check the presence of particular data.
     
  •  To prevent errors in the JSON data. 
     
  •  To check new updates in the data.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

JSONassert Library 

JSONassert library is a Java library that helps to implement JSON equality.

We can use it to compare JSON arrays using the JSONassert library in REST assured. It also helps to compare JSON Objects using the JSONassert library in REST assured.

For example:

A JSON array - [1,2,3,4] & [4,3,2,1]. The JSONassert library will tell the user if the given arrays are similar or not. 

JSONassert Library

It compares JSON with the existing JSON response in REST assured. This decreases the programmer's workload, and they don’t have to write several statements/logic to complete a few tasks.

JSONassert library provides two ways to check equality : 

  • assertEquals() method - compares JSON objects and JSON arrays.
     
  • JSONcomparemode - provides four different modes with different behaviors for JSON comparison. 
    A. Strict 
    B. Lenient 
    C. Non-extensible 
    D. Strict Order

Compare JSON Objects Using the JSONassert Library in REST Assured

As discussed above, we need to compare JSON objects using the JSONassert library in REST assured for a few important reasons.
We will use both methods mentioned in the “JSONassert library” section to compare JSON objects using the JSONassert library in REST assured.

Assertequals() Method

We can compare JSON objects using the JSONassert library in REST assured using the assertequals() method.

SYNTAX

JSONassert.assertEquals(<JSON object 1>, <JSON object 2 >, JSONCompareMode.<mode name>);


We can even use assertequals to give a mode of comparison.

SYNTAX

assertEquals(JSONobject 1 , JSONobject 2, <mode>);


It uses Boolean parameters to provide mode. We write the following to pass different modes:

  • False - non-strict mode or lenient mode.
     
  • True - strict mode OR Boolean strict - for strict mode.

Comparing JSON Object in LENIENT Mode

We use the lenient mode to compare JSON objects using the JSONassert library in REST assured because:

  • It provides extensibility.
     
  • No strict order of values in JSON objects is required.
     

In lenient mode, if we compare two:

  • Exactly the same JSON objects - JSON will pass. The implementation example is below.
     
@Test
public void exactSameJsonObjects() throws JSONException {

	String jsoNobject1 = "{\r\n" +
						"  \"firstName\" : \"Anchita\",\r\n" +
						"  \"lastName\": \"Sharma\"\r\n" +
						"  }";

	String jsonObject2 = "{\r\n" +
						"  \"firstName\" : \"Anchita\",\r\n" +
						"  \"lastName\": \"Sharma\"\r\n" +
						"}";

JSONAssert.assertEquals(jsoNobject1, jsonObject2, JSONCompareMode.LENIENT);
}


OUTPUT

output image
  • JSON objects with the same fields but different orders - JSON will pass. The implementation example is below.
     
@Test
public void exactSameJsonWIthDifferentOrder() throws JSONException {

	String jsoNobject1 = "{\r\n" +
						"  \"firstName\" : \"Anchita\",\r\n" +
						"  \"lastName\": \"Sharma\"\r\n" +
						"}";

	String jsonObject2 = "{\r\n" +
						"  \"lastName\": \"Sharma\",\r\n" +
						"  \"firstName\": \"Anchita\"\r\n" +
						"}";

JSONAssert.assertEquals(jsoNobject1, jsonObject2, JSONCompareMode.LENIENT);
}


OUTPUT

OUTPUT image
  • JSON objects with the same field but different values - JSON will give an error. This is because one value does not match. The implementation example is below.
     
@Test
public void sameFieldsWithDifferentValues() throws JSONException {

	String jsoNobject1 = "{\r\n" +
						"  \"firstName\" : \"Anchita\",\r\n" +
						"  \"lastName\": \"Sharma\"\r\n" +
						"}";

	String jsonObject2 = "{\r\n" +
						"  \"lastName\": \"Sharma\",\r\n" +
						"  \"firstName\": \"Pranshu\"\r\n" +
						"}";

JSONAssert.assertEquals(jsoNobject1, jsonObject2, JSONCompareMode.LENIENT);
}


OUTPUT

output image
  • JSON objects with the same field but different datatype of values- JSON will give an error. This is because to compare JSON objects using the JSONassert library even the data type of values need to be the same. The implementation example is below.
     
@Test
public void unmatchedDataType() throws JSONException {

	String jsoNobject1 = "{\r\n" +
						"  \"lastName\": \"Sharma\",\r\n" +
						"  \"firstName\": \"Anchita\",\r\n" +
						"  \"age\": \"19\"\r\n" +
						"}";

	String jsonObject2 = "{\r\n" +
						"  \"lastName\": \"Sharma\",\r\n" +
						"  \"firstName\": \"Anchita\",\r\n" +
						"  \"age\": 19\r\n" +
						"}";
// First json has 19 as string while second json has 19 as int
JSONAssert.assertEquals(jsoNobject1, jsonObject2, JSONCompareMode.LENIENT);
}


OUTPUT

output image

In this section, we learned that JSON will pass under lenient mode only if the JSON object is exactly the same and is not affected by the order of fields.

Comparing JSON Object in STRICT Mode

We use the lenient mode to compare JSON objects using the JSONassert library in REST assured because:

  • The strict order of fields of JSON object is to be compared.
     
  • No extensibility is required.
     

JSON is passed in this mode only when all fields, values, and datatype of values are exactly the same.

Handling Errors 

Sometimes while we compare JSON objects using the JSONassert library in REST assured it throws an assertion error. In case that error is needed to be ignored we use the try-catch method.

SYNTAX

try{JSONAssert.assertEquals(JSONobject1,JSONobject2,false);
}catch(Error e)


This will pass the JSON even if the error persists.

Compare JSON Arrays Using the JSONassert Library in REST Assured

As discussed above, in the “need for comparison” section we need to compare JSON arrays using the JSONassert library in REST assured for a few important reasons.

We will use both methods mentioned in the “JSONassert library” section to compare JSON arrays using the JSONassert library in REST assured.

Assertequals() Method

We can compare JSON arrays using the JSONassert library in REST assured using the assertequals() method.

SYNTAX

JSONassert.assertEquals(<JSON array 1>, <JSON array 2 >, JSONCompareMode.<mode name>);

Comparing JSON Arrays in LENIENT Mode

We use the lenient mode to compare JSON arrays using the JSONassert library in REST assured because:

  • Provides extensibility.
     
  • No strict order of values in JSON arrays is required.
     

In lenient mode, if we compare two JSON arrays:

  • An equal number of elements, values and same order- JSON will pass. The implementation example is below.
     
@Test
public void unmatchedDataType() throws JSONException {

	// Equal no of elements, values with same order
	String jsonArray1 = "[\"Anchita\",\"Anshit\",\"Stuti\"]";
	String jsonArray2 = "[\"Anchita\",\"Anshit\",\"Stuti\"]";

	JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}


OUTPUT

output image
  • An equal number of elements with different values - JSON will fail because it will return an unexpected element error. The implementation example is below.
     
@Test
public void unmatchedDataType() throws JSONException {

	// Equal no of elements, values with different values
	String jsonArray1 = "[\"Anchita\",\"Anshit\",\"Stuti\"]";
	String jsonArray2 = "[\"Anchita Sharma\",\"Anshit\",\"Stuti\"]";

	JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}


OUTPUT

output image
  • An equal number of elements with different case values -  JSON will fail. This is because it is case-sensitive. The implementation example is below.
     
@Test
public void unmatchedDataType() throws JSONException {

	// Equal no of elements with different case values
	String jsonArray1 = "[\"Anchita\",\"Anshit\",\"Stuti\"]";
	String jsonArray2 = "[\"ANCHITA\",\"Anshit\",\"Stuti\"]";

	JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}


OUTPUT

output image
  • An equal number of elements with different order- JSON will pass. The implementation example is below.
     
@Test
public void unmatchedDataType() throws JSONException {

	// Equal no of elements with different order
	String jsonArray1 = "[\"Anchita\",\"Anshit\",\"Stuti\"]";
	String jsonArray2 = "[\"Stuti\",\"Anchita\",\"Anshit\"]";

	JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}


OUTPUT

output image
  • An equal number of elements with all different values - JSON will fail. The implementation example is below.
     
@Test
public void unmatchedDataType() throws JSONException {

	// Equal no of elements with all different values
	String jsonArray1 = "[\"Anchita\",\"Anshit\",\"Stuti\"]";
	String jsonArray2 = "[\"Shiv\",\"Akash\",\"Sneha\"]";

	JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}


OUTPUT

output image
  • A different number of elements - JSON will fail. This will give expected values exceeded error. The implementation example is below.
     
@Test
public void unmatchedDataType() throws JSONException {

	// Different no. of elements
	String jsonArray1 = "[\"Anchita\",\"Anshit\",\"Stuti\"]";
	String jsonArray2 = "[\"Anchita\",\"Anshit\",\"Stuti\",\”Shiv\”]";

	JSONAssert.assertEquals(jsonArray1, jsonArray2, JSONCompareMode.LENIENT);
}


OUTPUT

output image

In this section, we learned that JSON will pass under lenient mode only if the JSON array is exactly the same and it is not affected by the order of elements.

Comparing JSON Arrays in STRICT Mode

We use the strict mode to compare JSON arrays using the JSONassert library in REST assured because:

  • The strict order of values and elements is followed.
     
  • If values are in a sequence.
     

JSON is passed in this mode only when all elements, values, and order of values are exactly the same. Returns the index of the value that does not match when a JSON fails.

Must Read Array of Objects in Java

Let's discuss some FAQs.

Frequently Asked Questions

Are REST assured and REST API the same?

A Java library called REST Assured is used to test RESTful APIs. It is frequently used to test web applications that handle JSON and XML. Additionally, it supports all RESTful methods, including PUT, GET, PATCH, POST, and DELETE.

Why is JSON used over XML?

JSON is designed for data interchange. Thus it is faster than XML. Moreover, JSON can be parsed by a javascript function. At the same time, XML requires an XML parser.

Which is better, postman or rest assured?

Rest assured is better than the postman. Rest assured, you can reuse code as it is a Java client. Moreover, in postman, we can provide only one data file for each collection, unlike rest assured.

What are {} and [] used in JSONpath expressions for?

JSONpath expressions is a query language for JSON. It uses [] for JSON objects. And it uses {} for arrays in JSONpath expressions.

Is JSON secure or free from viruses?

JSON can be hijacked and is not completely free from viruses either. The attacker targets a system with access to JSON data. And then can retrieve data from a JSON file.

Conclusion

This article discussed the need for a comparison of JSON data. We learned about the JSONassert library and how to use it to compare JSON objects using the JSONassert library in REST assured and to compare JSON arrays using the JSONassert library in REST assured.
To learn more about REST assured, refer to

Recommended problems -

 

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Previous article
REST Assured – Compare Two JSON using Jackson – Java Library
Next article
REST Assured - How To Compare Part of JSON Objects and Arrays using JSONassert library
Live masterclass