2016-08-12 1 views
0

Ich brauche Hilfe beim Ersetzen von Daten innerhalb einer JSON-Datei mit NODE.JS. Meine aktuelle Methode fügt sie mit der gleichen ID hinzu, die korrekt ist. Wenn die Daten jedoch zurück empfangen werden, löscht es das letzte Duplikat, weil es zuerst den alten Wert gefunden hat. Ich denke, was ich wirklich tun muss, ist JSON-Element nach ID auswählen. Dann ersetzen Sie es durch das neue.Node.JS Ajax zum Ersetzen vorhandener JSON-Daten

Hier ist meine AJAX Anfrage:

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

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

Hier ist es, die Daten mit doppelten ids:

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

Ich denke, was ich wirklich tun muss, ist JSON Element nach ID auswählen. Dann ersetzen Sie es durch das neue. –

Antwort

1

Sind Sie gerade versuchen, den Artikel zu ersetzen, wenn es existiert ts? Wenn ja, könnten Sie etwas tun:

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

Nun ja in gewissem Sinne, aber sie werden nicht genau gleich sein. Der Inhalt wird anders sein. Die ID wird gleich sein. –