javascript - 将 javascript 对象附加到 json 文件
问题描述
我正在返回一个 javascript 对象,并尝试使用fs.appendFile
. 当我在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))
})
推荐阅读
- c++ - 为什么 Visual Studio 无法在模板类中选择正确的构造函数?
- reactjs - 将电子应用程序发布到 Windows 商店时如何修复“可用的应用程序图标包括默认图标”?
- android - 导航应该弹回堆栈而不是返回起始目的地
- android - 如何使用 azure sql 连接和访问(如编辑)
- vue.js - Font Awesome vue js Layers 创建了导致 Vue Bootstrap 中不需要的间距的工件
- controller - UICloudSharingController 在 Xcode 11 中显示无限活动指示
- swiftui - 导航按钮无法关闭模式
- ios - 如何在 Developer Portal 中辨别用于签署配置文件的签名身份
- mule - Mule Web 服务消费者社区版 3.9
- html - Thymeleaf 没有用 ajax 调用替换片段