从 *.txt 文件更新多个 *json 文件

Updating multiple *json files from *.txt file

我有几个 json 文件,每个文件包含以下行

"description": "Example",

我需要用文本文件中的一行更新每个 json 文件中的此字段,例如,文本文件包含以下内容,每行包含在单独的行中。

蓝色牛仔裤

红夹克

帽子

衬衫

碎花连衣裙

羊毛夹克

绿带

鞋子

橙色衬衫

腰带

我正在尝试查看是否有一种方法或脚本可以让每个 json 文件通过文本文件并更新描述字段,1.json 文件将 return 文本文件等中的第 1 行项目并一直进行直到完成,10.json 将更新为 *.txt 文件等中的第 10 行项目

ie 文件 3.json 将 "description": "Example", 更新为 "description": "Hat",

如有任何帮助,我们将不胜感激

谢谢

一种方法是读取每个文件,解析它,然后更新您需要更新的内容,最后再次将其写回磁盘。 这是我的 test.js 脚本:

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();
})();

我已经用文件对其进行了测试:

1.json

{ "description": "Example" }

2.json

{ "description": "Example2" }

然后我 运行 使用 node test.js 的脚本,结果如​​下:

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"
}

编辑

正如您在评论中提到的,您想从此处的文本文件中读取 replacements 您需要添加到之前代码的内容。

replacements.txt

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

这里是填充 replacements 数组的代码,前提是你有上面的文件,每个元素都在一个新行上,正如你在评论中描述的那样:

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/);