我正在运行快递节点服务器,我使用
$.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 :(得分: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;
});
});
});
答案 1 :(得分:0)
app.put('/edit/:id', (req,res) => {
var id = req.params.id;
var fname = req.body.fname;
var lname = req.body.lname;
var age = req.body.age;
var address = req.body.address;
var phone = req.body.phone;
jsonfile.readFile("./users.json", function(err,data) {
var fileObj = data;
fileObj.users_array.map((curr) => {
if(curr.id == id) {
curr.fname = fname;
curr.lname = lname;
curr.age = age;
curr.address = address;
curr.phone = phone;
}
});
jsonfile.writeFile('./users.json', fileObj, function(err) {
if(err) throw err;
});
});