簡體   English   中英

將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()方法 ,即可將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()方法,其中顯示:

請注意,對同一文件多次使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM