Zed Evans
Zed Evans

Reputation: 136

add key:value to a .json file

I have this config.json file:

{
  "account_name": {
    "min_len": "3",
    "max_len": "15",
    "upperCase": true,
    "lowerCase": true,
    "numbers": true,
    "specialChar": false,
    "capitalize": false,
    "duplication": false,
    "startWithCapital": false
  },
  "password": {
    "min_len": "6",
    "max_len": "20",
    "upperCase": true,
    "lowerCase": true,
    "numbers": true,
    "specialChar": true,
    "capitalize": false,
    "duplication": false,
    "StartWithCapital": false
  }
}

How can I add other values to this .json file from the code? for exapmle :

var keysOpt = require('../config/config.json');
KeysOpt.name = "eric"
KeyPot.save() // will save the new field to the file itself

Upvotes: 1

Views: 3257

Answers (2)

cнŝdk
cнŝdk

Reputation: 32145

You just need to use fs.writeFile() method, to write back the JSON to the file.

This is how will be your code:

var keysOpt = require('../config/config.json');
keysOpt = JSON.parse(keysOpt);
KeysOpt.name = "eric";
// Make whatever changes you want to the parsed data
fs.writeFile('../config/config.json', JSON.stringify(keysOpt));

Explanation:

You just need to :

  1. Parse the content of your JSON file, so you will get a JavaScript object.
  2. You can then modify it or extend it with new data.
  3. Before writing it back to the file you just need to make it a JSON string back again.
  4. And finally write it back to the JSON file with writeFile() method.

Note:

  • Note that you need to use writeFileSyn() to Synchronously write data to the file.
  • And you should be aware that you should wait for the writeFile() callback to finish writing if you will try to write more than once to the same file.

You can check the nodeJS documentation for fs.writeFile() method, where it says:

Note that it is unsafe to use fs.writeFile multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.

Upvotes: 3

Ezzat
Ezzat

Reputation: 911

You can do something simple like this :

var fs = require('fs');
var keysOpt = JSON.parse(fs.readFileSync('../config/config.json'));
KeysOpt.name = "eric";
fs.writeFileSync('../config/config.json',JSON.stringify(KeysOpt,null,' '));

Upvotes: 0

Related Questions