Skip to content

Instantly share code, notes, and snippets.

@nflaig
Created July 11, 2023 09:44
Show Gist options
  • Save nflaig/bb8f7b9361fa80394800b5da501a91ec to your computer and use it in GitHub Desktop.
Save nflaig/bb8f7b9361fa80394800b5da501a91ec to your computer and use it in GitHub Desktop.
diff two json files
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