Last active
May 9, 2024 08:23
-
-
Save zjplab/a83db59e43d86502676155486e9c4639 to your computer and use it in GitHub Desktop.
JSON Schema Diff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function customDiff(obj1, obj2) { | |
const result = {}; | |
// Helper function to check if a value is considered 'empty' | |
function isEmpty(val) { | |
return val === null || val === ""; | |
} | |
// Recursive function to find differences | |
function findDifferences(lhs, rhs, path = '') { | |
const checkedKeys = new Set(); | |
// Check keys from both objects | |
const keys = new Set([...Object.keys(lhs), ...Object.keys(rhs)]); | |
keys.forEach(key => { | |
const currentPath = path ? `${path}.${key}` : key; | |
checkedKeys.add(key); | |
// Check for presence in both objects | |
if (key in lhs && !(key in rhs)) { | |
result[currentPath] = { message: 'Key missing in second object', value: lhs[key] }; | |
return; | |
} | |
if (!(key in lhs) && key in rhs) { | |
result[currentPath] = { message: 'Key missing in first object', value: rhs[key] }; | |
return; | |
} | |
const lhsVal = lhs[key]; | |
const rhsVal = rhs[key]; | |
// Check for arrays with different lengths | |
if (Array.isArray(lhsVal) && Array.isArray(rhsVal)) { | |
if (lhsVal.length !== rhsVal.length) { | |
result[currentPath] = { message: 'Array lengths differ', lhsLength: lhsVal.length, rhsLength: rhsVal.length }; | |
} | |
return; | |
} | |
// Check for empty equivalence | |
if (isEmpty(lhsVal) && isEmpty(rhsVal)) { | |
return; // Ignore empty equivalence | |
} | |
// Recurse if both are objects and not arrays | |
if (typeof lhsVal === 'object' && lhsVal !== null && typeof rhsVal === 'object' && rhsVal !== null) { | |
findDifferences(lhsVal, rhsVal, currentPath); | |
return; | |
} | |
// Finally, check for equality of values | |
if (lhsVal !== rhsVal) { | |
// Ignoring differences in values | |
return; | |
} | |
}); | |
} | |
findDifferences(obj1, obj2); | |
return result; | |
} | |
// Example usage | |
const obj1 = { | |
details: { | |
info: "test", | |
moreInfo: [1, 2, 3] | |
} | |
}; | |
const obj2 = { | |
details: { | |
info: "test", | |
moreInfo: [1, 2, 3, 4] | |
} | |
}; | |
const differences = customDiff(obj1, obj2); | |
console.log(differences); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to compare Schema Differeences in JSON?
1. Arrays are compared based on length only, regardless of their contents.
2. Null and empty strings are considered equivalent to each other in any comparison.
3. All other value differences are ignored, focusing solely on structural and presence-related differences.