Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deterministically verify that a JSON object hasn't been modified?

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?

like image 578
aw crud Avatar asked Jan 19 '12 19:01

aw crud


People also ask

What is toJSON () in JSON?

if you need to read or clone all of a model's data attributes, use its toJSON() method. This method returns a copy of the attributes as an object (not a JSON string despite its name). (When JSON.

How do you check if a JSON object exists or not?

has() method – Class JsonObject. This is the convenience method that can be used to check of a property/member with the specified key is present in the JsonObject or not. This method returns true if the member with specified key exists, otherwise it returns false.

How does Indexeddb store JSON data?

A method to add a JSON object to the database and store it in the object store we created earlier follows. You can create an object with key value pairs, get the object store and call the add() method to add the object to the object store. Consequently, you can create two handlers: on success and on error.

How do I check if a string is valid in JSON?

To check if a string is JSON in JavaScript, we can use the JSON. parse method within a try-catch block. to check if jsonStr is a valid JSON string. Since we created the JSON string by calling JSON.


1 Answers

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.

like image 98
Daff Avatar answered Sep 28 '22 17:09

Daff