I am loading JSON when web page loaded and it is changed through user actions in the client. When user navigate away want to see if the JSON is changed or not. Instead of comparing values one by one inside the JSON is the any way to make a hash string and compare as a whole in JavaScript?
Asked
Active
Viewed 1.3k times
4
-
Who is generating the two JSON? (the old and the new) are both generated by JS code? – xanatos Aug 22 '13 at 07:03
-
1Since JSON is really just a string in JS, you could simply compare the final string with the original string. However, if you parse the JSON in between, modify the object and then convert the object back to JSON, there is no guarantee that the properties will be listed in the same order. But parsing the original JSON string and converting the object back to JSON with JS should circumvent that problem. – Felix Kling Aug 22 '13 at 07:06
-
@xanatos One is returned from server and loaded when user works on the app the JSON will be updated time to time. – Nish Aug 22 '13 at 08:44
-
@FelixKling I will go with the JSON.stringify as you said. – Nish Aug 22 '13 at 08:45
3 Answers
10
Try using stringified versions of the data
Ex.
JSON.stringify(orig) == JSON.stringify(current)
Note: in this case you need to keep a deep copy of the original json or a stringified version of it, also there is a possibility of false positive because the order of keys might get changed.
For browsers which does not support native JSON, you may have to use a library like json2.

Mike Cluck
- 31,869
- 13
- 80
- 91

Arun P Johny
- 384,651
- 66
- 527
- 531
-
2*"the order of keys might get changed"* I think this could only happen if the original JSON is generated somewhere else, e.g. a PHP script. Calling `JSON.stringify` on the same data should produce the same result every time. Related: http://stackoverflow.com/questions/8931967/is-there-a-deterministic-equivalent-of-json-stringify. I hope MDN refers to differences between engines, the same engine should always produce the same result. – Felix Kling Aug 22 '13 at 07:09
-
Is it possible to do without retaining the entire original? Is there a way to retain just a hash of the original and then compare with a hash of the new? – Kwhitejr Aug 03 '18 at 14:59
6
And, there is another way:
assign the two JSON's to two objects, a and b.
Now, you can do a deep-equal
comparison using underscorejs or lodash functions.
_.isEqual(a, b)

kumarharsh
- 18,961
- 8
- 72
- 100
4
You can use JSON.stringify()
from json2.js
.
if (JSON.stringify(object1) == JSON.stringify(object2)) {
//magic
}
(Some browsers don't even need json2.js, as they support JSON.stringify
natively)

h2ooooooo
- 39,111
- 8
- 68
- 102