Skip to content

Instantly share code, notes, and snippets.

@carlflor
Created July 6, 2023 16:54
Show Gist options
  • Save carlflor/d88981645dc4135d5b37396c611469bd to your computer and use it in GitHub Desktop.
Save carlflor/d88981645dc4135d5b37396c611469bd to your computer and use it in GitHub Desktop.
compare if two json strings are similar
function areJsonStringsSimilar(jsonString1, jsonString2) {
function areArraysSimilar(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i++) {
if (typeof arr1[i] === 'object') {
if (!areObjectsSimilar(arr1[i], arr2[i])) return false;
} else if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
function areObjectsSimilar(obj1, obj2) {
const keys1 = Object.keys(obj1).sort();
const keys2 = Object.keys(obj2).sort();
if (keys1.length !== keys2.length) {
return false;
}
for (let i = 0; i < keys1.length; i++) {
if (keys1[i] !== keys2[i]) {
return false;
}
const value1 = obj1[keys1[i]];
const value2 = obj2[keys2[i]];
if (typeof value1 !== typeof value2) {
return false;
}
if (Array.isArray(value1) && Array.isArray(value2)) {
if (!areArraysSimilar(value1, value2)) {
return false;
}
} else if (typeof value1 === 'object') {
if (!areObjectsSimilar(value1, value2)) {
return false;
}
} else if (value1 !== value2) {
return false;
}
}
return true;
}
try {
const obj1 = JSON.parse(jsonString1);
const obj2 = JSON.parse(jsonString2);
return areObjectsSimilar(obj1, obj2);
} catch (error) {
console.error('Invalid JSON strings:', error.message);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment