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.

Gokhan Oner
  • 3,237
  • 19
  • 25

2 Answers2

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

kaz
  • 1,190
  • 8
  • 19
  • 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 ? – Gokhan Oner May 18 '15 at 17:59
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>
Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73