Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two JSON have the same properties without order?

I have tried to compare those two JSON objects:

<input type="hidden" id="remoteJSON" name="remoteJSON" value='{"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"}' /><br /> <input type="hidden" id="localJSON" name="localJSON" value='{"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"}' /><br /> 

I got values with javascript and I tried to compare with : JSON.stringify(remoteJSON) == JSON.stringify(localJSON) but this return false: it seems that the order of the properties is important.

And I even tried deep compare with this solution and always got a false return.

Is there a fast way to do the issue with jQuery (i.e. libraries for comparing JSON) ?

like image 319
Drwhite Avatar asked Sep 25 '14 22:09

Drwhite


People also ask

How do you compare two JSON objects with the same elements in a different order equal?

To compare two JSON objects with the same elements in a different order equal with Python, we can load the JSON strings into dicts with json. loads . Then we can sort the items with sorted and then compare them. to load the JSON strings into dicts with json.

How do you compare two JSON objects?

Comparing Json: Comparing json is quite simple, we can use '==' operator, Note: '==' and 'is' operator are not same, '==' operator is use to check equality of values , whereas 'is' operator is used to check reference equality, hence one should use '==' operator, 'is' operator will not give expected result.

Does order of JSON properties matter?

Any error or exception? The JSON RFC (RFC 4627) says that order of object members does not matter.


2 Answers

Lodash _.isEqual allows you to do that:

var  remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"},      localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"};        console.log( _.isEqual(remoteJSON, localJSON) );
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
like image 144
Nicolas Avatar answered Sep 19 '22 06:09

Nicolas


Lodash isEqual() method is the best way to compare two JSON object.

This will not consider the order of the keys in object and check for the equality of object. Example

const object1 = {   name: 'ABC',   address: 'India' };      const object2 = {   address: 'India',   name: 'ABC' };      JSON.stringify(object1) === JSON.stringify(object2) // false      _.isEqual(object1, object2) // true 

Reference - https://lodash.com/docs/#isEqual

If sequence is not going to change than JSON.stringify() will be fast as compared to Lodash's isEqual() method.

Reference - https://www.measurethat.net/Benchmarks/Show/1854/0/lodash-isequal-test

like image 28
Ashita.gupta Avatar answered Sep 18 '22 06:09

Ashita.gupta