简体   繁体   中英

Append javascript object to json file

I'm returning a javascript object and I'm trying to append it to a json file using fs.appendFile . When I test the output of the file at, json formatter website , I get the error Multiple JSON root elements . Can someone please show me what I'm doing wrong here.

var data = {
  userProfile: {
    name: "Eric"
  },
  purchases: [
    {
      title: "book name"
    },
    {
      title: "book name two"
    }
  ]
};

fs.appendFile("data.json", JSON.stringify(data, null, 2), function(err) {
  if (err) {
    console.log("There was an error writing the backup json file.", err);
  }
  console.log("The backup json file has been written.");
});

You neede to open your file, parse the JSON, append your new data to the old data, transform it back into a string and save it again.

var fs = require('fs')

var newData = {
  userProfile: {
    name: "Eric"
  },
  purchases: [
    {
      title: "book name"
    },
    {
      title: "book name two"
    }
  ]
};

fs.readFile('data.json', function (err, data) {
    var json = JSON.parse(data)
    const newJSON = Object.assign(json, newData)
    fs.writeFile("data.json", JSON.stringify(newJSON))
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM