我使用以下代码将数据发布到 json 文件:
let productObj= {
description: req.body.description,
quality: req.body.quality
};
fs.readFile('products.json', function (err, data) {
let jsone= JSON.stringify(productObj);
console.log(jsone);
fs.appendFile("results.json", jsone, function(err){
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
});
});
正如我在控制台中看到的那样,POST 成功。但是在 json 文件中,数据附加在子对象之外。
products.json:
{
"products":[
{
"description": "Apples",
"quality": "High",
},
{
"description": "Oranges",
"quality": "low",
}
]}
最佳答案
appendFile
将现有内容与新内容连接起来。假设如下:
- 旧数据:
ABC
- 新数据:
XYZ
- 最终数据:
ABCXYZ
在您的情况下,内容类型是 JSON,需要采用某种格式 - appendFile
与 contentType
无关,这意味着您必须正确格式化现有数据集/将现有数据集与新数据集合并,并将其保存回文件。
尝试下一个代码
let productObj= {
description: req.body.description,
quality: req.body.quality
};
fs.readFile('products.json', function (err, data) {
// Convert string (old data) to JSON
let result = JSON.parse(data);
// Add new data to result
result.products.push(productObj);
// Convert JSON to string
let jsone= JSON.stringify(result);
console.log(jsone);
// Replace all data in the results.json with new ones
fs.writeFile("results.json", jsone, function(err){
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
});
关于node.js - json 文件无法使用appendfile 正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52751521/