2

Im looking for a way to compare 2 json records on screen. The way i want is that, i want to show these 2 records side by side and mark the matched or unmatched properties.

Is there a library that does it already, and if not, how can i do it ??

Edit

My goal is to identify the same/different properties & to show them to users with different styles, rather than comparing the objects as a whole.

2
  • possible duplicate of Compare 2 JSON objects Commented May 18, 2015 at 17:14
  • Yes agree this is duplicate question Commented May 18, 2015 at 17:24

2 Answers 2

1

Someone made a jQuery plugin for this - jQuery.PrettyTextDiff.

https://github.com/arnab/jQuery.PrettyTextDiff

$("input[type=button]").click(function () { $("#wrapper tr").prettyTextDiff({ cleanup: $("#cleanup").is(":checked") }); }); 

JSFiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer @kaz. Instead of a diff section, is it possible to use colours on "Original" and "Changed" columns ? If the text is different, I can change all text to red, instead of showing the difference ? And color ir as green if all is same ?
1

Here is a quick JavaScript function to help you compare the to JSON strings.

First, it checks that they have same number of properties, then compares that they have the same properties (by name) and then it compares the values.

You may want to tweak the value comparison (to allow for undefined or null).

Hope it is a good starter for you.

<script type="text/javascript"> var so = {}; // stackoverflow, of course. so.compare = function (left, right) { // parse JSON to JavaScript objects var leftObj = JSON.parse(left); var rightObj = JSON.parse(right); // add object properties to separate arrays. var leftProps = []; var rightProps = []; for(var p in leftObj) { leftProps.push(p); } for(var p in rightObj) { rightProps.push(p); } // do they have the same number of properties if (leftProps.length != rightProps.length) return false; // is every right property found on the left for (var r = 0; r < rightProps.length; r++) { var prop = rightProps[r]; if (leftProps.indexOf(prop) < 0) { return false; } } // is every left property found on the right for (var r = 0; r < leftProps.length; r++) { var prop = leftProps[r]; if (rightProps.indexOf(prop) < 0) { return false; } } // do the values match? for (var q = 0; q < leftProps.length; q++) { var propname = leftProps[q]; var leftVal = leftObj[propname]; var rightVal = rightObj[propname]; if (leftVal != rightVal) { return false; } } return true; } </script> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.