Created
July 6, 2023 16:54
-
-
Save carlflor/d88981645dc4135d5b37396c611469bd to your computer and use it in GitHub Desktop.
compare if two json strings are similar
This file contains 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 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