Compare 2 JSON objects [duplicate]

非 Y 不嫁゛ 提交于 2019-11-26 07:38:11

问题


Possible Duplicate:
Object comparison in JavaScript

Is there any method that takes in 2 JSON objects and compares the 2 to see if any data has changed?

Edit

After reviewing the comments, some clarification is needed.

  1. A JSON object is defined as

    \"an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).\" -- json.org

  2. My goal is to be able to compare 2 JSON object literals, simply put.

I am not a javascript guru so if, in javascript, these are object literals, then I suppose that\'s what I should call them.

I believe what I am looking for is a method capable of:

  1. Deep recursion to find a unique name/value pair
  2. Determine the length of both object literals, and compare the name/value pairs to see if a discrepancy exists in either.

回答1:


Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...


来源:https://stackoverflow.com/questions/4465244/compare-2-json-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!