【问题标题】:add key:value to a .json file将键:值添加到 .json 文件
【发布时间】:2017-10-17 12:40:25
【问题描述】:

我有这个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

【问题讨论】:

标签: javascript json node.js file fs


【解决方案1】:

您只需使用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() 如果您将尝试多次写入,则回调以完成写入 同一个文件。

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

请注意,在同一个文件上多次使用fs.writeFile 是不安全的 文件无需等待callback。对于这种情况, 强烈推荐fs.createWriteStream

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2018-01-25
      • 1970-01-01
      • 2020-11-30
      • 2022-01-18
      相关资源
      最近更新 更多