Skip to content

Instantly share code, notes, and snippets.

@nilscox
Last active March 29, 2022 13:57
Show Gist options
  • Select an option

  • Save nilscox/0c7830427b56047173f2f31caaa666d8 to your computer and use it in GitHub Desktop.

Select an option

Save nilscox/0c7830427b56047173f2f31caaa666d8 to your computer and use it in GitHub Desktop.
replace all ids of a JSON file with new UUIDs
#!/usr/bin/env node
const crypto = require("crypto");
const fs = require("fs");
const replaceIds = (obj) => {
if (typeof obj !== "object" || obj === null) {
return obj;
}
for (const [key, value] of Object.entries(obj)) {
if (key === "id" && typeof value === "string") {
obj[key] = crypto.randomUUID();
} else if (typeof value === "object") {
replaceIds(obj[key]);
}
}
return obj;
};
const main = async (argv) => {
const [, , ...args] = argv;
if (args.length === 0) {
throw new Error("missing input file");
}
const file = await fs.promises.readFile(args[0]);
const json = JSON.parse(String(file));
console.log(JSON.stringify(replaceIds(json), null, 2));
};
main(process.argv).catch((error) => {
console.error(error);
process.exitCode = 1;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment