我有这个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));
说明:
您只需要:
- 解析 JSON 文件的内容,这样您将获得一个 JavaScript
对象
。 - 然后您可以修改它或使用新数据扩展它。
- 在将其写回文件之前,您只需将其设为 再次返回 JSON 字符串。
- 最后使用
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 thecallback
. For this scenario,fs.createWriteStream
is strongly recommended.
关于javascript - 添加 key :value to a . json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035219/