简体   繁体   中英

Node.JS ajax to replace existing JSON data

I need help replacing data inside of a JSON file using NODE.JS. My current method adds it with the same ID which is correct. However, when the data is received back, it drops the last duplicate because it found the old value first. I think what I really need to do is select JSON element by ID. Then replace it with the new.

Here is my AJAX request:

putComment: function(commentJSON, success, error) {
    $.ajax({
        type: 'post',
        url: 'http://localhost:8080',
        data: JSON.stringify(commentJSON),
        success: function(comment) {
            success(comment)
        },
        error: error
    });
},

Here's my NODE :

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"}');
});
};

Here is the data with duplicate id's:

[
  {
    "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
  }
]

Are you just trying to replace the item if it exists? If so, you could do something like this:

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!");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM