6

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

medemi68
  • 175
  • 1
  • 1
  • 8
  • Do you want to do this at run time or at build time? – moarboilerplate Apr 23 '15 at 20:29
  • you HAVE to rewrite it since there is always going to be a terminator at the end of the JSON file (either `"`, `]`, `}`) and you need to put things inside it – Plato Apr 23 '15 at 20:32
  • Ok, Is there a way to rewrite it but keep the existing data? – medemi68 Apr 23 '15 at 20:32
  • I don't care about rewriting the file, It just needs to be easy and done in as minimal lines of code possible.. I also need to be able to retain the data. – medemi68 Apr 23 '15 at 20:34

1 Answers1

11

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});
Plato
  • 10,812
  • 2
  • 41
  • 61
  • Gave me " Object # has no method 'push' – medemi68 Apr 23 '15 at 20:49
  • ok, well, thats because objects have no method 'push'... Either use an array instead or explictly set a key/value on the object: `config['user3624610'] = {name: 'bob', code: 'abc'}` – Plato Apr 23 '15 at 23:51
  • -1 for suggesting `readFileSync` and `writeFileSync`. Please don't fight against the NodeJS async nature. It will only hurt yourself :P You should only use this methods when strictly necessary. And this is not the case. – Ze Luis Jan 08 '16 at 11:35
  • 1
    @ZeLuis he asked for simple, easy, minimal lines of sample code, that doesn't make a synchronous solution "dangerously incorrect" – Plato Jan 08 '16 at 11:55
  • How about really big JSON files ! – Ahmed Eid Jun 30 '17 at 16:47