Add to JSON file (Node.JS, Javascript)

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

{ "OnetimeCode" : "Value" } 

And I would like to be able to do two things:

  • Add to file (change values ​​in file)
  • Add new items to the file (in the same format)

I searched for almost an hour, trying to find either a module (for Node) or just a simple code example that would allow me to execute this.

I already tried to use several plugins, but instead of adding 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 this does not seem to work.

Any help is appreciated! But please keep it simple.

Also: I can not use jQuery

+5
source share
1 answer

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

With raw Node calls (if the json file is an array representation):

 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}); 
+9
source

All Articles