【问题标题】:How to add comma separator when appending JSON objects with node.js fs.appendFile?使用node.js fs.appendFile附加JSON对象时如何添加逗号分隔符?
【发布时间】:2021-07-29 09:27:09
【问题描述】:

我正在遍历文件夹中包含的所有图像,对于每个图像,我需要将其路径、日期(空)和布尔值添加到对象 JSON 中。

这是代码:

files.forEach(file => {
  fs.appendFile(
    'images.json', JSON.stringify({directory: `${sourcePathDesktopWin}/${folder}/${file}`, posted: false, date: null}, null, 2), (err) => {
      if (err) throw err;
      console.log(`The ${file} has been saved!`);
    }
  );
});

这是结果:

{
  "directory": "D:/directory1/test1.jpg",
  "posted": false,
  "date": null
}{
  "directory": "D:/directory1/test2.jpg",
  "posted": false,
  "date": null
}

正如您在附加时所看到的,它不会在每个 JSON 对象之间添加逗号分隔符。 如何添加?

【问题讨论】:

  • 在 JSON 对象之间添加逗号将使 images.json 无法作为格式正确的文件。您是否希望 images.json 成为格式正确的文件,并简单地将 files.forEach 中的每个文件附加到 images.json 文件中的 JSON 对象?

标签: javascript node.js json append


【解决方案1】:

在您当前的示例中,只需添加一个逗号就会使其成为无效的 JSON,正如已经指出的那样。但是,如果将其设为数组,则结果将是一个有效对象。

最简单的方法是创建一个空数组并将每个 JSON 对象推送给它。

images = [];
files.forEach(file => {
  images.push({directory: `${sourcePathDesktopWin}/${folder}/${file}`, posted: false, date: null})  
});

然后您可以将此数组写入文件。你的结果是:

[
  {
    "directory": "D:/directory1/test1.jpg",
    "posted": false,
    "date": null
  },
  {
    "directory": "D:/directory1/test2.jpg",
    "posted": false,
    "date": null
  }
]

【讨论】:

    【解决方案2】:

    在我的例子中,在 JSON.stringify() 的第一个参数之后放置一个+ ',' 解决了这个问题

    你的代码应该是这样的

    files.forEach(file => {
      fs.appendFile(
        'images.json', JSON.stringify({directory: `${sourcePathDesktopWin}/${folder}/${file}`, posted: false, date: null}, null, 2) + ',', (err) => {
          if (err) throw err;
          console.log(`The ${file} has been saved!`);
        }
      );
    });
    

    【讨论】:

      猜你喜欢
      • 2020-07-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多