javascript - 添加 key :value to a . json 文件

标签 javascript json node.js file fs

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

关于javascript - 添加 key :value to a . json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035219/

相关文章:

javascript - 如何创建模态图像网格?

javascript - 如何在 Angular 中动态删除 css?

javascript - HTML5 localStorage : Big JSON, 特定值作为更改 CSS 的条件(收藏夹列表)

arrays - 异步等待 JSON 解析不等待

angularjs - 移动应用程序如何在本地存储消息?

node.js - 将 MongoDB 从本地主机迁移到服务器

javascript - YUP 验证期间出错 "Cannot read property ' 长度'未定义”

javascript - 为什么没有 'var' 关键字的变量不在 Chrome 控制台的全局范围内?

json - 如何混合来自jq的json级别

ajax - CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符