[英]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()方法 ,即可將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));
說明:
您只需要:
object
。 writeFile()
方法將其寫回到JSON文件中。 注意:
writeFileSyn()
來將數據同步寫入文件。 writeFile()
回調完成寫入。 您可以在nodeJS文檔中查看fs.writeFile()
方法,其中顯示:
請注意,對同一文件多次使用
fs.writeFile
而不等待callback
是不安全的。 對於這種情況,強烈建議使用fs.createWriteStream
。
您可以執行以下簡單操作:
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,' '));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.