如何将 JSON 数据附加到现有 JSON 文件 node.js

Tcm*_*mxc 5 json append node.js stringify

如何使用逗号“,”作为分隔符附加现有 JSON 文件

anchors = [ {  "title":"  2.0 Wireless " }  ]
fs.appendFileSync('testOutput.json', JSON.stringify(anchors));
Run Code Online (Sandbox Code Playgroud)

当前代码的输出是这样的

[
   {
     "title":"  2.0 Wireless "
   }
 ]
 [
   {
     "title":"  Marshall Major II "
   }
]
Run Code Online (Sandbox Code Playgroud)

如何使用逗号“,”作为分隔符以正确的格式获取此内容

我想要得到这样的东西

[
   {    
    "title":"  2.0 Wireless "
   },
   {
     "title":"  Marshall Major II "
   }
]
Run Code Online (Sandbox Code Playgroud)

小智 5

尝试这个。不要忘记定义anchors数组。

var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);

fs.writeFile("testOutput.json", JSON.stringify(json))
Run Code Online (Sandbox Code Playgroud)