2016-08-12 1 views
0

NODE.JSを使用してJSONファイル内のデータを置換するのに役立つ必要があります。私の現在のメソッドは、同じIDで正しいものを追加します。ただし、データが戻されると、古い値が最初に検出されたため、最後の重複が削除されます。 JSON要素をIDで選択するだけで本当に必要なことだと思います。その後、新しいものと交換してください。ここでNode.JS既存のJSONデータを置換するためのajax

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

私が本当に必要とするのは、IDでJSON要素を選択することです。その後、新しいものと交換してください。 –

答えて

1

はあなただけです

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

ここに私のNODEだ:ここでは

は私のAJAX要求でありますもし存在すればそのアイテムを置き換えようとするTS?もしそうなら、次のようなことをすることができます:

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

ある意味ではいですが、まったく同じではありません。内容は異なるでしょう。 IDは同じです。 –

関連する問題