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

发布于 2025-01-23 18:52:41 字数 426 浏览 4 评论 0原文

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

"description": "Example",

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

蓝色牛仔裤

红色外套

帽子

衬衫

花卉连衣裙

毛门夹克

绿带

橙色衬衫

我想看看是否有一个方法或脚本,每个json文件都可以通过文本文件并更新描述字段,1.JSON文件将从文本文件等返回行项目1,并完成工作直到完成,10.JSON将从 *.txt文件等订单10中更新

。 “,已更新为“描述”:“ HAT”,

任何帮助都将不胜

感激

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

复古式 2025-01-30 18:52:41

一种方法是读取每个文件,解析它,然后更新您需要更新的内容,然后最终将其再次写回磁盘。
这是我的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" }

然后我使用节点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.txt

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

在此处填充替换的代码给定的阵列上述文件,每个元素都在新行上,如您在评论中所述:

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

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/); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文