簡體   English   中英

將 javascript 對象附加到 json 文件

[英]Append javascript object to json file

我正在返回一個 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.");
});

您需要打開文件,解析 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))
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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