Updating multiple *json files from *.txt file

Viewed 108

I have several json files, each file contains the following line

"description": "Example",

I need to update this field in each json file with a line from the text file, as an example the text file has the following, each contained on a separate line.

Blue Jeans

Red Jacket

Hat

Shirt

Floral Dress

Wollen Jacket

Green belt

Shoes

Orange Shirt

Belt

I'm trying to see if there is a way or script that for each json file to go through the text file and update the description field, 1.json file would return line item 1 from the text file etc and work its way through until completed, 10.json would update with line item 10 from the *.txt file etc

ie file 3.json would have "description": "Example", updated to "description": "Hat",

Any help would be appreciated

Thanks

1 Answers

One way to do it is to read each file, parse it, then update what you need to update and then finally write it back to disk again. Here my test.js script:

import { readFile, writeFile } from "fs/promises";

async function replaceInFiles(){
  const replacements = ["Blue Jeans", "Red Jacket", "Hat", "Shirt", "Floral Dress", "Wollen Jacket", "Green belt", "Shoes", "Orange Shirt", "Belt"]
  await Promise.all(replacements.map(async (replaceWith, idx) => {
    const filename = `${idx + 1}.json`;
    // read file
    let file;
    try {
      file = await readFile(filename);
    } catch (error) {
      console.log(`Failed to read ${filename}. ${error}`)
      return;
    }
    // parse content
    const parsed = JSON.parse(file);
    // replace description
    parsed.description = replaceWith;
    // write updated file with intendation of 4
    try {
      await writeFile(filename, JSON.stringify(parsed, null, 4));
    } catch (error) {
      console.log(`Failed to write ${filename}. ${error}`)
      return;
    }
    console.log(`Updated ${filename}.`);
  }));
  console.log("Done.")
}

(async () => {
  await replaceInFiles();
})();

I have tested it with to files:

1.json

{ "description": "Example" }

2.json

{ "description": "Example2" }

Then I run the script using node test.js and this result in the following:

Console

Failed to read 3.json. Error: ENOENT: no such file or directory, open '3.json'
Failed to read 4.json. Error: ENOENT: no such file or directory, open '4.json'
Failed to read 5.json. Error: ENOENT: no such file or directory, open '5.json'
Failed to read 6.json. Error: ENOENT: no such file or directory, open '6.json'
Failed to read 7.json. Error: ENOENT: no such file or directory, open '7.json'
Failed to read 9.json. Error: ENOENT: no such file or directory, open '9.json'
Failed to read 8.json. Error: ENOENT: no such file or directory, open '8.json'
Failed to read 10.json. Error: ENOENT: no such file or directory, open '10.json'
Updated 1.json.
Updated 2.json.
Done.

1.json

{
    "description": "Blue Jeans"
}

2.json

{
    "description": "Red Jacket"
}

Edit

As you've mentioned in the comment you want to read the replacements from a text file here what you need to add to the previous code.

replacements.txt

Blue Jeans
Red Jacket
Hat
Shirt
Floral Dress
Wollen Jacket
Green belt
Shoes
Orange Shirt
Belt

Here the code to populate the replacements array given you have above file with every element being on a new line as you've described in your comment:

const replacementStr = await readFile("replacements.txt", { encoding: "utf8" });
const replacements = replacementStr.split("\n");
// to make the split work for any OS no matter the line endings you can use
const replacements = replacementStr.split(/\r?\n|\r/); 
Related