How to append JSON data to existing JSON file node.js

主宰稳场 提交于 2020-01-24 19:49:28

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/50747537/how-to-append-json-data-to-existing-json-file-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!