Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to a JSON File (Node.JS, Javascript) [duplicate]

I currently have a json file setup with the following format:

{
   "OnetimeCode" : "Value"
}

And I'd like to be able to do two things:

  • Append to the file (change the values in the file)
  • Add New Items to the File (In the same format)

I have been searching for almost an hour trying to find either a module (for Node) or just easy sample code that would allow me to accomplish this.

I have tried using several plugins already, but rather than appending to the file, they completely rewrite it.

One of the plugins is called "jsonfile" (npm install jsonfile)

var jf = require('jsonfile'); // Requires Reading/Writing JSON    
var jsonStr = WEAS_ConfigFile;
        var obj = JSON.parse(jsonStr);
        obj.push({OnetimeCode : WEAS_Server_NewOneTimeCode});
        jf.writeFileSync(WEAS_ConfigFile, obj); // Writes object to file

But that does not seem to be working.

Any help is appreciated! But Please, keep it simple.

Also: I cannot use jQuery

like image 863
medemi68 Avatar asked Apr 23 '15 20:04

medemi68


1 Answers

The code you provided with the jsonfile library looks like a good start: you parse the json into an object, call .push(), and save something.

With raw Node calls (assuming the json file is a representation of an array):

var fs = require('fs');
function appendObject(obj){
  var configFile = fs.readFileSync('./config.json');
  var config = JSON.parse(configFile);
  config.push(obj);
  var configJSON = JSON.stringify(config);
  fs.writeFileSync('./config.json', configJSON);
}

appendObject({OnetimeCode : WEAS_Server_NewOneTimeCode});
like image 78
Plato Avatar answered Sep 19 '22 23:09

Plato