如何更新json文件中的值并通过node.js保存?我有文件内容:
var file_content = fs.readFileSync(filename);
var content = JSON.parse(file_content);
var val1 = content.val1;
Run Code Online (Sandbox Code Playgroud)
现在我想更改值val1并将其保存到文件中.
Set*_*eth 95
异步执行此操作非常简单.如果你担心阻塞线程(可能),它会特别有用.
var fs = require('fs');
var fileName = './file.json';
var file = require(fileName);
file.key = "new value";
fs.writeFile(fileName, JSON.stringify(file), function (err) {
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
});
Run Code Online (Sandbox Code Playgroud)
需要注意的是,json在一行上写入文件而不是美化.例如:
{
"key": "value"
}
Run Code Online (Sandbox Code Playgroud)
将会...
{"key": "value"}
Run Code Online (Sandbox Code Playgroud)
要避免这种情况,只需添加这两个额外的参数即可 JSON.stringify
JSON.stringify(file, null, 2)
Run Code Online (Sandbox Code Playgroud)
null - 代表替换器功能.(在这种情况下,我们不想改变过程)
2 - 表示缩进的空格.
Pet*_*ons 40
//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));
Run Code Online (Sandbox Code Playgroud)
除了上一个答案之外,为写操作添加文件路径目录
fs.writeFile(path.join(__dirname,jsonPath), JSON.stringify(newFileData), function (err) {}
Run Code Online (Sandbox Code Playgroud)
// read file and make object
let content = JSON.parse(fs.readFileSync('file.json', 'utf8'));
// edit or add property
content.expiry_date = 999999999999;
//write file
fs.writeFileSync('file.json', JSON.stringify(content));
Run Code Online (Sandbox Code Playgroud)