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

11,149

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))
Share:
11,149
Tcmxc
Author by

Tcmxc

Updated on June 04, 2022

Comments

  • Tcmxc
    Tcmxc almost 2 years

    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 "
       }
    ]
    
  • Tcmxc
    Tcmxc almost 6 years
    This almost works my out put looks like this [ { "title":" 2.0 Wireless " }, [{ "title":" Marshall Major II " }] ]