【发布时间】:2016-12-07 13:08:55
【问题描述】:
如何使用 NodeJS 将旧的 json 对象替换为新的更新对象?
现在,当我更新 json 文件时,它会将新数据与旧数据一起保存。
JSON:
[ {
"id": 1,
"name": "Sven",
"phone": "123123"
},
{
"id": 2,
"name": "Martin",
"phone": "2342342"
} ]
这是我的代码:
var operation = POST.operation; // POST request comes with operation = update/insert/delete
if (operation == 'update') {
fs.readFile("file.json", "utf8", function (err, data) {
var jsonFileArr = [];
jsonFileArr = JSON.parse(data); //Parse the data from JSON file
var haveId = jsonFileArr.some(function (obj){ // Checks if the POST request have the same id as JSON file
return obj.id == POST.id;
})
if (haveId) { // if true
var updateData = []; // Array with POST data
updateData.push({
id: POST.id,
name: POST.name,
phone: POST.phone,
})
jsonFileArr.push(updateData);
var newUsers = JSON.stringify(jsonFileArr);
fs.writeFile("file.json", newUsers, "utf8");
console.log(err);
}
})
}
我可能应该使用delete object,但我如何指定应该删除的对象?
所以当我用 id 1 更新数据时,它会删除旧的 id/姓名/电话并写入新数据。
【问题讨论】:
标签: javascript json node.js crud