How to compare two json objects ignoring the order of fields

Hello everyone,

I’m passing a request body with a JSON object containing n number of fields.

The body format is included in the body and this specific JSON object is in the pre-requisite script.

Upon hitting the post request an ID gets generated.

Now, I use get API with this ID to fetch the response.

Till now it’s all good.

As part of the test, I need to validate the response of the get API containing the JSON node that is passed as part of the prerequisite script.

methods that I have tried:

prerequisite step -

var employeedetails = { “id” = “12”, “location” = “USA”}


this fails because in the response body, the employeedetails JSON object displays the fields in a different order like

“body”: xxxxx,
“location” = “USA”,
“id” = “12”,

the second method that I have tried is
extracting this specific node from the response and comparing it with the node passed in the request.

var jsonData = JSON.parse(responsebody);
var response = jsonData.employeedetails;
var responseNode = JSON.stringify(response)

._equals (employeedetails, responseNode)

this returns true even when the fields are missing/different.

What I’m looking for is
the comparison should verify the count of elements in the request vs response matching
the key-value pairs are matching, regardless of the order in the request vs response

only when these conditions are true, does the function have to return true.

Your help is highly appreciated!! :slight_smile:

You can’t guarantee the order of the keys in an JavaScript object.

Therefore you will need to create an array of the keys, which you can then sort before you make the comparison.

Consider the following example…

var employeedetails = { "id": "12", "location": "USA" };

const response = pm.response.json().employeedetails;

let expectedResult = Object.keys(employeedetails).sort();
let actualResult = Object.keys(response).sort();

pm.test("response keys match", function () {

You might also want to consider using JSONSchema to validate the JSON structure.

Schema validation — Postman Quick Reference Guide Version 1.9.1 - January 2023 documentation (

The “expect” functionality is part of the Chai Assertion Library.

The deep equal" option will test for equality without regard to field order.


1 Like


Learn something every day. Something to remember in the future.

var employeedetails = { "id": "12", "location": "USA" };

const response = pm.response.json().employeedetails;

pm.test("response keys match - deep includes", function () {

I tested this by changing the keys and values, and it appears to work correctly.

At which point I noticed that my earlier post was not working correctly, as it was only checking the key names. :face_with_open_eyes_and_hand_over_mouth:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.