2

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.");
});
1

1 Answer 1

3

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))
})
Sign up to request clarification or add additional context in comments.

5 Comments

For some reason, this code doesn't append the new data. It seems to overnight the old data with the new data.
The same as newData
You can't have two sample key (for example userProfile in 1 JSON). Is your root object an array or just an object?
It's an object. Should it be an array?
It depends on your purpose. It you want a list of users, then it should be an array. Then const newJSON = json.push(newData) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.