2016-01-22 36 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

相关问题