【发布时间】:2016-08-12 19:58:34
【问题描述】:
我需要帮助使用 NODE.JS 替换 JSON 文件中的数据。我当前的方法使用相同的 ID 添加它,这是正确的。但是,当接收回数据时,它会丢弃最后一个副本,因为它首先找到了旧值。我认为我真正需要做的是按 ID 选择 JSON 元素。然后用新的替换它。
这是我的 AJAX 请求:
putComment: function(commentJSON, success, error) {
$.ajax({
type: 'post',
url: 'http://localhost:8080',
data: JSON.stringify(commentJSON),
success: function(comment) {
success(comment)
},
error: error
});
},
这是我的节点:
if (req.method == 'POST') {
req.on('data', function(chunk) {
var element = JSON.parse(chunk);
fs.readFile("comments-data.json", 'utf8', function(err, json) {
var array = JSON.parse(json);
array.push(element);
fs.writeFile("comments-data.json", JSON.stringify(array), function(err) {
if (err) {
console.log(err);
return;
}
console.log("The file was saved!");
});
});
res.end('{"msg": "success"}');
});
};
这是具有重复 id 的数据:
[
{
"id": "c1",
"parent": null,
"created": "2016-08-12T19:57:21.282Z",
"modified": "2016-08-12T19:57:21.282Z",
"content": "test",
"fullname": "John Clark",
"profile_picture_url": "https://viima-app.s3.amazonaws.com/media/user_profiles/user-icon.png",
"created_by_current_user": true,
"upvote_count": 0,
"user_has_upvoted": false
},
{
"id": "c1",
"parent": null,
"created": "2016-08-12T19:57:21.282Z",
"modified": 1471031853696,
"content": "test 123",
"fullname": "John Clark",
"profile_picture_url": "https://viima-app.s3.amazonaws.com/media/user_profiles/user-icon.png",
"created_by_current_user": true,
"upvote_count": 0,
"user_has_upvoted": false
}
]
【问题讨论】:
-
我认为我真正需要做的是按 ID 选择 JSON 元素。然后用新的替换它。
标签: javascript json ajax node.js