-3

It's probably something ridiculous I'm missing out, but when I add an object to my json file with NodeJs it adds it (obviously?) at the end of the file and so after ]

var file = './data/questions.json';    
fs.appendFile(file, ', ' + JSON.stringify(req.body), function (err) {
    console.log(err);
});

result is something like this:

[
{'id':1, 'name':'Tom'}
], {'id':2, 'name':'Jerry'}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Greg
  • 1,382
  • 3
  • 22
  • 45

2 Answers2

6

If the file already has an array in it already, what you need is:

var file = './data/questions.json';
// get the contents of the file
var fileContents = do_something_to_get_contents;
// convert to js object
fileContents = JSON.parse(fileContents);
// push the array
fileContents = fileContents.push(req.body);
// update the file contents by stringify
fs.replaceFile(file, JSON.stringify(fileContents), function (err) {
    console.log(err);
});

I am not so good in Node JS. So I am assuming the following:

  1. do_something_to_get_contents gets the file contents.
  2. replaceFile Replace this with a function that writes fresh contents to the file.
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
2

You need to parse the JSON file to add to it. Try something like this:

var file = './data/questions.json';
var fileData = get_data_from_file
var jData = JSON.parse(file);
jData.push({'id':2, 'name':'Jerry'});
var newFileData = JSON.stringify(jData);
//put the data back into the file
Blubberguy22
  • 1,344
  • 1
  • 17
  • 29
  • Er, no. `JSON.parse(file)` will attempt to parse `./data/questions.json`, not the **contents** of the file. You'll need to read it first. And I guess the OP also wants the resulting JSON-encoded data to be written to a file. – jcaron Jan 15 '16 at 14:22
  • @jcaron Good point, my bad, I didn't notice that. I'll fix it, thanks. – Blubberguy22 Jan 15 '16 at 14:23