2016-01-22 20 views
4

上我正在快速結點服務器,我使用Node.js加載如何刪除編輯數據的JSON文件中的服務器

 $.ajax({ 
      url: this.props.url, 
      dataType: 'json', 
      cache: false, 
      success: function(data) { 
       this.setState({data: data}); 
      }.bind(this), 
      error: function(xhr, status, err) { 
       console.error(this.props.url, status, err.toString()); 
      }.bind(this) 
     }); 

獲取服務器裏面JSON數據。 JSON數據是這樣的:

[ 
{ 
    "id": 1453464243666, 
    "text": "abc" 
}, 
{ 
    "id": 1453464256143, 
    "text": "def" 
}, 
{ 
    "id": 1453464265564, 
    "text": "ghi" 
} 
] 

如何(執行什麼要求),刪除\修改任何物體在此JSON?

+0

你有在後臺的JSON文件讀取,將文本轉換爲對象,編輯對象,然後用編輯的對象重新編寫JSON文件。 – usandfriends

+0

@usandfriends,所以我需要發送請求完整覆蓋服務器上的JSON? – Syberic

+0

是的,它很sl。。如果您要編輯大量的JSON,我建議切換到數據庫,以便編輯更高效。但是,爲此,您必須編寫一個API來將您的前端與數據庫連接起來。 – usandfriends

回答

2

要閱讀JSON文件,您可以使用jsonfile模塊。然後您需要在快速服務器上定義put路由。代碼爲特快服務器凸顯了主要部件的片段:

app.js

// This assumes you've already installed 'jsonfile' via npm 
var jsonfile = require('jsonfile'); 

// This assumes you've already created an app using Express. 
// You'll need to pass the 'id' of the object you need to edit in 
// the 'PUT' request from the client. 
app.put('/edit/:id', function(req, res) { 
    var id = req.params.id; 
    var newText = req.body.text; 

    // read in the JSON file 
    jsonfile.readFile('/path/to/file.json', function(err, obj) { 
     // Using another variable to prevent confusion. 
     var fileObj = obj; 

     // Modify the text at the appropriate id 
     fileObj[id].text = newText; 

     // Write the modified obj to the file 
     jsonfile.writeFile('/path/to/file.json', fileObj, function(err) { 
      if (err) throw err; 
     }); 
    }); 
}); 
+0

謝謝,我明白了。 – Syberic

相關問題