将javascript对象添加到json文件中

问题描述 投票:0回答:1

我正在返回一个javascript对象,并尝试使用fs.appendFile将其附加到json文件中。当我在json formatter website处测试文件的输出时,出现错误Multiple JSON root elements。有人可以告诉我我在做什么错。

var data = {
  userProfile: {
    name: "Eric"
  },
  purchases: [
    {
      title: "book name"
    },
    {
      title: "book name two"
    }
  ]
};

fs.appendFile("data.json", JSON.stringify(data, null, 2), function(err) {
  if (err) {
    console.log("There was an error writing the backup json file.", err);
  }
  console.log("The backup json file has been written.");
});
javascript node.js
1个回答
0
投票

您需要打开文件,解析JSON,将新数据附加到旧数据,将其转换回字符串,然后再次保存。

var fs = require('fs')

var newData = {
  userProfile: {
    name: "Eric"
  },
  purchases: [
    {
      title: "book name"
    },
    {
      title: "book name two"
    }
  ]
};

fs.readFile('data.json', function (err, data) {
    var json = JSON.parse(data)
    const newJSON = Object.assign(json, newData)
    fs.writeFile("data.json", JSON.stringify(newJSON))
})
© www.soinside.com 2019 - 2024. All rights reserved.