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

前端 未结 8 1764
忘了有多久
忘了有多久 2020-11-30 04:38

According to MDN documentation for JSON.stringify:

Properties of non-array objects are not guaranteed to be stringified in any particular order. Do

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 05:00

    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.

提交回复
热议问题