gpt4 book ai didi

javascript - 将 javascript 对象附加到 json 文件

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:41 26 4
gpt4 key购买 nike

我正在返回一个 javascript 对象,并尝试使用 fs.appendFile 将其附加到 json 文件。当我在 json formatter website 测试文件的输出时,我收到错误多个 JSON 根元素。有人可以告诉我我在这里做错了什么吗?

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))
})

关于javascript - 将 javascript 对象附加到 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59419188/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com