最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js how to deleteedit data inside json file on the server - Stack Overflow

programmeradmin0浏览0评论

I'm running express node server and i use

        $.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)
        });

to GET data inside json on the server. json with data looks like:

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

How (what request to perform) to delete\modify any object in this json?

I'm running express node server and i use

        $.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)
        });

to GET data inside json on the server. json with data looks like:

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

How (what request to perform) to delete\modify any object in this json?

Share Improve this question asked Jan 22, 2016 at 20:00 Ilya LopukhinIlya Lopukhin 6928 silver badges23 bronze badges 5
  • You have to read in the JSON file in the backend, convert the text to an object, edit the object, and then re-write the JSON file with the edited object. – rgajrawala Commented Jan 22, 2016 at 20:06
  • @usandfriends so i need to sent request for plete overwriting json on the server? – Ilya Lopukhin Commented Jan 22, 2016 at 20:07
  • Yeah, it's pretty sloppy. If you're going to be editing a lot of JSON, I suggest switching over to a database so editing is more efficient. However, for that, you'll have to write an API to interface your front-end with your database. – rgajrawala Commented Jan 22, 2016 at 20:10
  • @usandfriends i want this quick functionality for education process, i definitely WILL use some database later, but now i need just this. Can you tell exact request i need to send to rewrite full json file on the server? – Ilya Lopukhin Commented Jan 22, 2016 at 20:14
  • 2 It isn't as simple as just sending a different request. You need to write some path handler on your HTTP server (like /edit-json) where you would send the name of the JSON file and the new contents through $.ajax. In the backend, you receive the new data and the file name and use fs.writeFile with JSON.stringify. Of course, there's a bunch of security issues and things you would have to check for, but since you wanted a quick solution for educational purposes, here it is. – rgajrawala Commented Jan 22, 2016 at 20:27
Add a ment  | 

2 Answers 2

Reset to default 3

To read the JSON file, you can make use of the jsonfile module. You then need to define a put route on the express server. A snippet of code for the express server highlighting the vital parts:

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;
      });
    });
});
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;
    });
});
发布评论

评论列表(0)

  1. 暂无评论