将 key:value 添加到 .json 文件

add key:value to a .json file

我有这个 config.json 文件:

{
  "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
  }
}

如何从代码向这个 .json 文件添加其他值? 例如:

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

您只需要使用 fs.writeFile() method,将 JSON 写回文件。

这就是您的代码:

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));

解释:

您只需要:

  1. 解析你的 JSON 文件的内容,所以你会得到 JavaScript object.
  2. 然后您可以修改它或使用新数据扩展它。
  3. 在将其写回文件之前,您只需要将其设为 JSON 字符串又回来了。
  4. 最后用writeFile()方法写回JSON文件。

注:

  • 注意需要使用writeFileSyn()才能同步写入 数据到文件。
  • 你应该知道你应该等待 writeFile() 如果您尝试多次写入,则回调完成写入 同一个文件。

您可以查看 nodeJS 文档中的 fs.writeFile() 方法,它说:

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.

你可以像这样做一些简单的事情:

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,' '));