如何在解码和编码后检查 JSON 是否相等
How to check equality of JSON after decoding and encoding
data = {
json: 'is life'
};
anoth = JSON.parse(JSON.stringify(data));
if (data == anoth){
console.log("yes")
}else{
console.log("nah")
}
console.log(data, anoth)
它们显然是相等的,但为什么它在代码中不起作用
因为您正在相互比较对象引用。当您反序列化原始序列化 JSON 对象时,会返回一个新的不同对象。两者内容相同,但是是不同的对象实例。如果你比较 JSON.stringify() 版本你会得到一个匹配。
data = {
json: 'is life'
};
anoth = JSON.parse(JSON.stringify(data));
if (data == anoth){
alert("Objects are same.")
}else{
alert("Objects are not same.")
}
if (JSON.stringify(data) == JSON.stringify(anoth)){
alert("Content is same")
}else{
alert("Content is not same.")
}
alert(JSON.stringify(data) + "\n" + JSON.stringify(anoth))
您应该比较两个对象是否相等,但在您的示例中您只比较引用 Object comparison in JavaScript
data = {
json: 'is life'
};
anoth = JSON.parse(JSON.stringify(data));
if (data == anoth){
console.log("yes")
}else{
console.log("nah")
}
console.log(data, anoth)
它们显然是相等的,但为什么它在代码中不起作用
因为您正在相互比较对象引用。当您反序列化原始序列化 JSON 对象时,会返回一个新的不同对象。两者内容相同,但是是不同的对象实例。如果你比较 JSON.stringify() 版本你会得到一个匹配。
data = {
json: 'is life'
};
anoth = JSON.parse(JSON.stringify(data));
if (data == anoth){
alert("Objects are same.")
}else{
alert("Objects are not same.")
}
if (JSON.stringify(data) == JSON.stringify(anoth)){
alert("Content is same")
}else{
alert("Content is not same.")
}
alert(JSON.stringify(data) + "\n" + JSON.stringify(anoth))
您应该比较两个对象是否相等,但在您的示例中您只比较引用 Object comparison in JavaScript