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) ?
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.
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.
Any error or exception? The JSON RFC (RFC 4627) says that order of object members does not matter.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With