Doug
Doug

Reputation: 1515

Generate diff JSON

I'm trying to create a function that will do a deep comparison of two JSON objects (objectA vs. objectB). And then generate a unique JSON object that only has the node tree to different data values.

My idea was to ship parts of the JSON into a recursive function, coupled with an array that held the data path. But when I run the code as I have it written, I am getting extra elements in my path array.

The end result ideally will provide a path like:
[ "level1c", "level2b", "level3c" ]
but unfortunately I am getting:
[ "level1a", "level1b", "level1c", "level2b", "level3c" ]

Once, I had a solid data path, then I was going to take that to build a new JSON object that only includes the nodes that differ.

function compareJSON( primary, secondary ){

    function diffJSON( primary, secondary, path ){

        var p = path.slice(); // copy array

        var keys = Object.keys( secondary );
        var sVal;
        var pVal;

        for( var i=0, x=keys.length; i<x; i++ ){

            sVal = secondary[keys[i]];
            pVal = primary[keys[i]];

            if( sVal !== pVal ){
                p.push( keys[i] );
                if( typeof sVal === 'object' && !Array.isArray( sVal ) ){
                    diffJSON( pVal, sVal, p );
                }else{
                    if( Array.isArray( sVal ) ){
                        compareArray( sVal, pVal, p );
                    }else{
                        updateResult( sVal, p );
                    }// END if( !Array.isArray() )
                }// END if( typeof sVal === 'object' ... )
            }// END if( sVal !== pVal )

        }// END for loop

        function compareArray( arr, arr2, path ){
            // compare arrays
        }

        function updateResult( data, path ){
            console.log( data, path );
        }// END function updateResult()

    }// END function diffJSON()

    diffJSON( primary, secondary, [] );

}// END function compareJSON()

Additional info:

Here's the code in practice, it prints out into the console a value that's found to be different in json2 (compared to json1) and the associated path array:

'use strict';

function compareJSON( primary, secondary ){

	function diffJSON( primary, secondary, path ){

		var p = path.slice(); // copy array
		
		var keys = Object.keys( secondary );
		var sVal;
		var pVal;

		for( var i=0, x=keys.length; i<x; i++ ){
			
			sVal = secondary[keys[i]];
			pVal = primary[keys[i]];

			if( sVal !== pVal ){
				p.push( keys[i] );
				if( typeof sVal === 'object' && !Array.isArray( sVal ) ){
					diffJSON( pVal, sVal, p );
				}else{
					if( Array.isArray( sVal ) ){
						compareArray( sVal, pVal, p );
					}else{
						updateResult( sVal, p );
					}// END if( !Array.isArray() )
				}// END if( typeof sVal === 'object' ... )
			}// END if( sVal !== pVal )
      
		}// END for loop

		function compareArray( arr, arr2, path ){
			var match = true;
			for( var i=0, x=arr.length; i<x; i++ ){
				if( arr[i] !== arr2[i] ){
					match = false;
				}
			}
			if( !match ){
				updateResult( arr, path );
			}
		}
		
		function updateResult( data, path ){
			console.log( data, path );
		}// END function updateResult()

		
		
	}// END function diffJSON()

	diffJSON( primary, secondary, [] );
	
}// END function compareJSON()

var json1 = {
	level1a : {
		level2a : {
			level3a : 'apple',
			level3b : ['happy', 'happy', 'joy', 'joy'],
			level3c : {
				level4a : 'sleep'
			},
			level3d : true
		},
		level2b : 'music',
		level2c : {
			level3a : 'future',
			level3b : false,
			level3c : ['bear', 'camel', 'elephant']
		}
	},
	level1b : {
		level2a : 'jeopardy',
		level2b : 10200,
		level2c : true,
		level2d : {
			level3a : 'aliens',
			level3b : 'weekend'
		}
	},
	level1c : {
		level2a : 'fiber',
		level2b : [1, 2, 4, 5, 6]
	},
	level1d : ['apple', 'cat', 'baby'],
	level1e : true,
	level1f : {
		level2a : false,
		level2b : true,
		level2c : {
			level3a : 'naruto',
			level3b : 123,
			level3c : 'test',
			level3d : 'this',
			level3e : 'thing'
		},
		level2d : true
	}
};

var json2 = {
	level1a : {
		level2a : {
			level3a : 'apple',
			level3b : ['happy', 'happy', 'joy', 'joy'],
			level3c : {
				level4a : 'sleep'
			},
			level3d : true
		},
		level2b : 'music',
		level2c : {
			level3a : 'future',
			level3b : false,
			level3c : ['bear', 'camel', 'elephant', 'lion']
		}
	},
	level1b : {
		level2a : 'jeopardy',
		level2b : 10200,
		level2c : true,
		level2d : {
			level3a : 'ancient',
			level3b : 'weekend'
		}
	},
	level1c : {
		level2a : 'fiber',
		level2b : [1, 2, 4, 5, 6]
	},
	level1d : ['apple', 'cat', 'baby'],
	level1e : true,
	level1f : {
		level2a : false,
		level2b : true,
		level2c : {
			level3a : 'naruto',
			level3b : 123,
			level3c : 'spicy',
			level3d : 'this',
			level3e : 'thing'
		},
		level2d : true
	}
};

compareJSON( json1, json2 );

Thanks for your time and support :)

Upvotes: 2

Views: 1203

Answers (1)

Shyam Babu
Shyam Babu

Reputation: 1079

I've modified your code a little bit to split the variable that hold the path and array that hold all diffs.

I am assuming both structure are equivalent, otherwise you would need to do an intersect and diff on keys of a and b, print diffs separately and loop on intersect.

I am using Object.prototype.toString so that in future you might add more cases (switch case friendly if you wanna go that route) and to reduce the checks.

      //if you want you pass allDiffs and path here and enhance this function to print array positional diff also 
    var isEqualArrays = function compareArray( arr1, arr2 ){
               if(arr1.length !== arr2.length) return false;
    			var match = true;
    			for( var i=0, x=arr1.length; i<x; i++ ){
    				if( arr1[i] !== arr2[i] ){
    					match = false;
    				}
    			}
    			return match;
    		}
var toString = Object.prototype.toString;
    
function compare (a, b, allDiffs, previousPath) {
      var akeys = Object.keys(a);
      for (key of akeys) {
        var currentPath = previousPath.concat(key);
        var typeOfa = toString.call(a[key]);
        var typeOfb = toString.call(b[key]);
        if(typeOfa !== typeOfb) {
           allDiffs.push({path: currentPath, values: [a[key], b[key]] })
           continue
        }
        if(typeOfa === '[object Array]')  {
            if(!isEqualArrays(a[key], b[key])){//remove this if , if you want enhance route
               allDiffs.push({path: currentPath, values: [a[key], b[key]] })
            }
           continue;
         }
         if(typeOfa === '[object Object]') {
           compare(a[key], b[key], allDiffs, currentPath)
           continue
         }
         if(a[key] !== b[key]) {
            allDiffs.push({path: currentPath, values: [a[key], b[key]] })
         }
      }
    
      return allDiffs
 }
    
    var json1 = {
    	level1a : {
    		level2a : {
    			level3a : 'apple',
    			level3b : ['happy', 'happy', 'joy', 'joy'],
    			level3c : {
    				level4a : 'sleep'
    			},
    			level3d : true
    		},
    		level2b : 'music',
    		level2c : {
    			level3a : 'future',
    			level3b : false,
    			level3c : ['bear', 'camel', 'elephant']
    		}
    	},
    	level1b : {
    		level2a : 'jeopardy',
    		level2b : 10200,
    		level2c : true,
    		level2d : {
    			level3a : 'aliens',
    			level3b : 'weekend'
    		}
    	},
    	level1c : {
    		level2a : 'fiber',
    		level2b : [1, 2, 4, 5, 6]
    	},
    	level1d : ['apple', 'cat', 'baby'],
    	level1e : true,
    	level1f : {
    		level2a : false,
    		level2b : true,
    		level2c : {
    			level3a : 'naruto',
    			level3b : 123,
    			level3c : 'test',
    			level3d : 'this',
    			level3e : 'thing'
    		},
    		level2d : true
    	}
    };
    
    var json2 = {
    	level1a : {
    		level2a : {
    			level3a : 'apple',
    			level3b : ['happy', 'happy', 'joy', 'joy'],
    			level3c : {
    				level4a : 'sleep'
    			},
    			level3d : true
    		},
    		level2b : 'music',
    		level2c : {
    			level3a : 'future',
    			level3b : false,
    			level3c : ['bear', 'camel', 'elephant', 'lion']
    		}
    	},
    	level1b : {
    		level2a : 'jeopardy',
    		level2b : 10200,
    		level2c : true,
    		level2d : {
    			level3a : 'ancient',
    			level3b : 'weekend'
    		}
    	},
    	level1c : {
    		level2a : 'fiber',
    		level2b : [1, 2, 4, 5, 6]
    	},
    	level1d : ['apple', 'cat', 'baby'],
    	level1e : true,
    	level1f : {
    		level2a : false,
    		level2b : true,
    		level2c : {
    			level3a : 'naruto',
    			level3b : 123,
    			level3c : 'spicy',
    			level3d : 'this',
    			level3e : 'thing'
    		},
    		level2d : true
    	}
    };
    
    console.log(compare(json1, json2, [], []))

Upvotes: 1

Related Questions