Last active
March 29, 2022 13:57
-
-
Save nilscox/0c7830427b56047173f2f31caaa666d8 to your computer and use it in GitHub Desktop.
replace all ids of a JSON file with new UUIDs
This file contains hidden or 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
| #!/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