How to deterministically verify that a JSON object hasn't been modified?
javascript, json
Solution
I am pretty sure this is because of the way different JavaScript engines keep track of object properties internally. Take this for example:
var obj = {
"1" : "test",
"0" : "test 2"
};
for(var key in obj) {
console.log(key);
}
This will log 1, 0 in e.g. Firefox, but 0, 1 in V8 (Chrome and NodeJS). So if you need to be deterministic, you will probably have to iterate through each key store it in an array, sort the array and then stringify each property separately by looping through that array.
Problem
According to MDN documentation for JSON.stringify: Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification. I had hoped to determine if an object changed by caching a stringified version of the object, then comparing it to a subsequently stringified version of the object. That seemed much simpler than recursively iterating through the object and doing comparisons. The problem is that because the JSON.stringify function is not deterministic, I could technically get a different string when I stringify the same object. What other options do I have? Or do I have to write a nasty compare function to determine object equality?