Compare 2 JSON objects

Possible duplicate:
Comparing Objects in JavaScript

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

Edit

After considering the comments, some clarification is required.

  • The JSON object is defined as

    "an unordered set of name / value pairs. An object starts with {(left bracket) and ends with} (right curly bracket). Each name follows: (colon) and name / value pairs are separated, (comma)." - json.org

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

I am not a javascript guru, so if in javascript these are object literals, then I suppose I should name them.

I believe that I am looking for a method capable of:

  • Deep recursion to find a unique name / value pair
  • Determine the length of both object literals and compare the name / value pairs to see if a mismatch exists.
+44
json javascript compare
Dec 16 '10 at 20:49
source share
1 answer

Just parsing JSON and comparing two objects is not enough, because these will not be exact references to objects (but they can be the same values).

You need to do deep equality.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - this is similar to using 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)) ... 
+15
Dec 16 '10 at 21:02
source share



All Articles