node.js - json 文件无法使用appendfile 正确更新

标签 node.js json

我使用以下代码将数据发布到 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,需要采用某种格式 - appendFilecontentType 无关,这意味着您必须正确格式化现有数据集/将现有数据集与新数据集合并,并将其保存回文件。

尝试下一个代码

 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/

相关文章:

node.js - 删除node.js中的文件不起作用

node.js - 类型错误:无法读取未定义的属性 'getAppPath'

javascript - Node.js 在 API 调用返回后执行某些操作

javascript - 带有 reviver 参数的 JSON.parse 将对象字段列入白名单

javascript - AngularJS 绑定(bind)在 JSON 中的右圆括号上阻塞

jquery - MVC JavaScriptSerializer反序列化json

node.js - 在 mongoose/node REST 服务器中隐藏嵌入文档

javascript - NodeJS : child_process. exec 未执行函数

Python 按两个键值对 JSON 列表进行排序

Javascript:总和或所有数字在for循环中不起作用