[英]Append javascript object to json file
I'm returning a javascript object and I'm trying to append it to a json file using fs.appendFile
.我正在返回一个 javascript 对象,并尝试使用
fs.appendFile
将其附加到 json 文件中。 When I test the output of the file at, json formatter website , I get the error Multiple JSON root elements
.当我在json formatter website 上测试文件的输出时,出现错误
Multiple JSON root elements
。 Can someone please show me what I'm doing wrong here.有人可以告诉我我在这里做错了什么。
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.");
});
You neede to open your file, parse the JSON, append your new data to the old data, transform it back into a string and save it again.您需要打开文件,解析 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.