Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript JSON comparison/diff?

Tags:

Say I have the following 2 json objects:

JSON A:
{
"Field A":"1",
"Field B":"2",
"Field D":"Something",
"Field E":"6"
}

JSON B:
{
"Field A":"1",
"Field B":"2",
"Field C":"3",
"Field D":"Different"
}

Sample Function: function (jsonstringA, jsonstringB)

Example (If JSON A and JSON B used as parameters):

Returns a new JSON object containing:

{
"Field C":"3", // because function sees jsonstringB had no "Field C"
"Field D": "Different" // sees jsonstringB had a different value for "Field D"
}

Note that it is using jsonstringA as the base of the comparison, so the function returns only the fields missing and values of jsonStringB. That is why "Field E" and its value is not returned.

What is the best way if possible to come up with a function that returns a json object containing values that have changed?

WHAT I HAVE TRIED: I have tried doing a comparison by manually specifying the fields that I am trying to check for, but I would like to have something that requires me to not hardcode the "Fields" as it is very inefficient and everytime I add a new field to JSON B, I have to hardcode in the field I am looking for... that is why I am looking for something less of a pain.

like image 696
Rolando Avatar asked Apr 27 '12 21:04

Rolando


People also ask

How do you find the difference between two JSON files?

You can also directly compare two JSON files by specifying their urls in the GET parameters url1 and url2. Then you can visualize the differences between the two JSON documents. It highlights the elements which are different: Different value between the two JSON: highlight in red color.

What is JSON diff?

A diff takes two JSON objects and presents any differences between them. Diff has several uses. A key use is displaying a clear summary of differences between large objects, enhancing the visibility of changes. This enables manual, user-interface assisted, or client actions to resolve differences.

How do I compare two JSON objects in Node JS?

Your first code step would be to convert the JSON string to an object, using JSON. parse . Then you can use Object. keys to get all keys from the first object, and you can loop over these keys to see the difference in values in the two objects.


1 Answers

It's not too hard to create a function like this. Just loop through each field in the second object, and if it's not present in the first or the value is different than the first, put that field in the return object.

var compareJSON = function(obj1, obj2) {
  var ret = {};
  for(var i in obj2) {
    if(!obj1.hasOwnProperty(i) || obj2[i] !== obj1[i]) {
      ret[i] = obj2[i];
    }
  }
  return ret;
};

You can see it in action on this demo page.

like image 80
Peter Olson Avatar answered Sep 29 '22 11:09

Peter Olson