如何确定性地验证JSON对象是否未被修改? [英] How to deterministically verify that a JSON object hasn't been modified?

查看:120
本文介绍了如何确定性地验证JSON对象是否未被修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 JSON.stringify的MDN文档


无法保证非数组对象的属性按任何特定顺序进行字符串
。不要依赖
内的属性排序字符串化中的同一个对象。

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.

我原本希望确定一个对象通过缓存对象的字符串化版本,然后将其与随后的字符串化对象版本进行比较来更改。这似乎比递归迭代对象并进行比较要简单得多。问题是因为JSON.stringify函数不是确定性的,所以当我对同一个对象进行字符串化时,我可以在技术上得到一个不同的字符串。

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?

推荐答案

我很确定这是因为这种方式不同的JavaScript引擎在内部跟踪对象属性。以此为例:

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);
}

这将在例如1中记录1,0 Firefox,但在V8(Chrome和NodeJS)中为0,1。
因此,如果您需要确定性,您可能必须遍历数组中的每个密钥存储,对数组进行排序,然后通过循环遍历该数组来单独对每个属性进行字符串化。

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.

这篇关于如何确定性地验证JSON对象是否未被修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆