Created
July 11, 2023 09:44
-
-
Save nflaig/bb8f7b9361fa80394800b5da501a91ec to your computer and use it in GitHub Desktop.
diff two json files
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
import fs from "fs"; | |
function deepSort(obj) { | |
if (Array.isArray(obj)) { | |
return obj.map(deepSort).sort((a, b) => JSON.stringify(a) > JSON.stringify(b)); | |
} else if (typeof obj === "object" && obj !== null) { | |
return Object.keys(obj) | |
.sort() | |
.reduce((result, key) => { | |
result[key] = deepSort(obj[key]); | |
return result; | |
}, {}); | |
} else { | |
return obj; | |
} | |
} | |
function jsonDiff(json1, json2) { | |
let diff = {}; | |
json1 = deepSort(json1); | |
json2 = deepSort(json2); | |
for (let key in json1) { | |
if (!(key in json2)) { | |
diff[key] = json1[key]; | |
} else if (typeof json1[key] === "object" && typeof json2[key] === "object") { | |
let objDiff = jsonDiff(json1[key], json2[key]); | |
if (Object.keys(objDiff).length > 0) { | |
diff[key] = objDiff; | |
} | |
} else if (json1[key] !== json2[key]) { | |
diff[key] = json1[key]; | |
} | |
} | |
for (let key in json2) { | |
if (!(key in json1)) { | |
diff[key] = json2[key]; | |
} | |
} | |
return diff; | |
} | |
const json1 = JSON.parse(fs.readFileSync("./file1.json")); | |
const json2 = JSON.parse(fs.readFileSync("./file2.json")); | |
console.log(jsonDiff(json1, json2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment