【问题标题】:Node.JS ajax to replace existing JSON dataNode.JS ajax 替换现有 JSON 数据
【发布时间】: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


【解决方案1】:

您是否只是想替换该项目(如果存在)?如果是这样,你可以这样做:

var array = JSON.parse(json);
var isNew = true;
for (var i = 0; i < array.length; i++) {
   if (array[i].id === element.id) {
         array[i] = element;
         isNew = false;
         break;
    }
}
//doesn't exist yet
if (isNew) {
    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!");
});

【讨论】:

  • 从某种意义上说是的,但它们不会完全相同。内容会有所不同。 ID 将相同。
猜你喜欢
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 2018-11-17
  • 2016-09-03
  • 1970-01-01
  • 2015-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多