MaxBeauchemin
1/2/2019 - 7:42 PM

JSON String Compare in JavaScript

Need to see what has changed between 2 JSON strings? Use the following functionality to accomplish this

Note that this doesn't detect properties being added / removed from the object, but that can easily be added

var jsonStringA = '{"ID": 1,"Number": 3,"Boolean": true}';
var jsonStringB = '{"ID": 1,"Number": 5,"Boolean": false}';

var compareJson = function (a, b) {
    if (a == null || a == '') {
        'ITEM WAS ADDED'
        return;
    }

    if (b == null || b == '') {
        'ITEM WAS DELETED'
        return;
    }

    var aObj = JSON.parse(a);
    var bObj = JSON.parse(b);

    var output = [];

    for (var propA in aObj) {
        var existsInB = false;
        var valA = aObj[propA];
        for (var propB in bObj) {
            if (propA === propB) {
                existsInB = true;
                var valB = bObj[propB];

                if (valA !== valB) {
                    output.push({
                        Property: propA,
                        OldValue: valA,
                        NewValue: valB
                    });
                }
            }
        }
    }

    return output;
};

var result = compareJson(jsonStringA, jsonStringB);