且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-20 12:45:36

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

var data = fs.readFileSync('testOutput.json');var json = JSON.parse(data);json.push(...锚点);fs.writeFile("testOutput.json", JSON.stringify(json))

How to append an existing JSON file with comma "," as separator

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

This current code's output is like this

[
   {
     "title":"  2.0 Wireless "
   }
 ]
 [
   {
     "title":"  Marshall Major II "
   }
]

How to I get this in the correct format with comma "," as separator

I want to get something like this

[
   {    
    "title":"  2.0 Wireless "
   },
   {
     "title":"  Marshall Major II "
   }
]

Try this. Don't forget to define anchors array.

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

fs.writeFile("testOutput.json", JSON.stringify(json))