简体   繁体   中英

adding another entry to a .json file. NodeJS

I am using a JSON file to store some data, this is my current structure. created by my code attempts.

 {
  "Username": "ozziep",
  "ProjectID": "ExpressJS",
  "TimeStamp": "2016-12-30T19:54:52.418Z",
  "Comments": "hello world how are we today?"
}

{
  "Username": "alex",
  "ProjectID": "Foo",
  "TimeStamp": "2016-12-30T19:55:07.138Z",
  "Comments": "we need to double check that this json system works. "
}

I generate the JSON like this, not the best code, still learning JS.

var time = new Date();
    var project_id = data.postid;
    var comment = data.commentdata;
    var usercommented = data.usercoment
    fs.readFile("comments.json", 'utf-8', function(err, data) {
            if (err) {
                throw err;
            }
            if (typeof data !== "undefined") {
      var jsongrid = {
        "Username": usercommented,
        "ProjectID": project_id,
        "TimeStamp": time,
        "Comments": comment
      }
      //this all works, for now. and will hopefully stay that way.
      console.log(commentsdata)
      var JSONStringed = JSON.stringify(jsongrid, null, 4) //turning the json grid into JSON, and prettyprinting it. generates correct JSON
                var commentsdata = data; //current JSON on file.
      var CompiledJSON = "\n"+commentsdata + "\n "+JSONStringed;//adding the new to the old.
      var bCompiledJSON = "["+CompiledJSON+"\n]"
      fs.truncate('comments.json', 0, function(){console.log('comments file can now be written to.')})



    var time = new Date();
    var project_id = data.postid;
    var comment = data.commentdata;
    var usercommented = data.usercoment
    fs.readFile("comments.json", 'utf-8', function(err, data) {
            if (err) {
                throw err;
            }
            if (typeof data !== "undefined") {
      var jsongrid = {
        "Username": usercommented,
        "ProjectID": project_id,
        "TimeStamp": time,
        "Comments": comment
      }
      //this all works, for now. and will hopefully stay that way.
      console.log(commentsdata)
      var JSONStringed = JSON.stringify(jsongrid, null, 4) //turning the json grid into JSON, and prettyprinting it. generates correct JSON
                var commentsdata = data; //current JSON on file.
      var CompiledJSON = "\n"+commentsdata + "\n "+JSONStringed;//adding the new to the old.
      var bCompiledJSON = "["+CompiledJSON+"\n]"
      fs.truncate('comments.json', 0, function(){console.log('comments file can now be written to.')})

    //  var jsonsearched = CompiledJSON.hasOwnProperty("Vortex.API")
      console.log(CompiledJSON[2])
    //  var CompiledJsonPretty = JSON.stringify(CompiledJSON, null, 4); //pretty printing this creation.
                console.log("A user has submitted a comment to post " + project_id) //logging.
                console.log("Generating JSON")
      console.log(CompiledJSON)
      socket.emit("added_comment")

                    //  var json_temp = {"Comments":{"Username":usercommented,"CommentData":comment,"date":time,"ProjectID":project_id}}
                    //var jsondata = JSON.stringify(json_temp)


                console.log("--------------------------------------------")
                console.log("Temp JSON generated - value: \n\n" + JSONStringed)
                if (typeof JSONStringed !== "undefined") {
                    fs.writeFile("comments.json", bCompiledJSON, function(err) {
                        if (!err) {
                            //verify data has been written, cause comments are important!
                            fs.readFile("comments.json", 'utf-8', function(err, data) {
                                if (err) {
                                    throw err;
                                }
                                if (data !== CompiledJSON) {
                                    console.log("Writing comment JSON to file failed.")
                                    console.log("- \n if (data) !== JSONStringed; failed. ")
                                } else{
                socket.emit("added_comment")
              }
                            })
                        } else {
                            throw err;
                        }
                    })
                }
            }
        })
        //  console.log(JSON.stringify(json))
})

I do plan on minimising it a little, its too much code for something so simple, any way, it creates the JSON from the jsongrid writes to file, but the only problem is it writes them on top of each other, as shown above, this does not work because I am not able to pick out a block by name or what ever, I have tried just reading the file, erasing it, adding the [] to it, then writing the JSON to file again, but that just adds lots of [] around, which does not work either, I wanted to access the data in the JSON like, foo[1].Username for example. what is the best way to achieve this?

Simplest solution is to store an array of JSON objects in your file.

Keep in mind that although JSON stands for "JavaScript Object Notation," an array is also valid JSON. So your file could look like this:

[
  {
    "Username": "ozziep",
    "ProjectID": "ExpressJS",
    "TimeStamp": "2016-12-30T19:54:52.418Z",
    "Comments": "hello world how are we today?"
  },
  {
    "Username": "alex",
    "ProjectID": "Foo",
    "TimeStamp": "2016-12-30T19:55:07.138Z",
    "Comments": "we need to double check that this json system works. "
  }
]

Then to add, remove, lookup objects in the file, you read the entire file in, parse it, and do what you need.

Adding a comment:

var time = new Date();
var project_id = data.postid;
var comment = data.commentdata;
var usercommented = data.usercoment
// Read in whole file
fs.readFile("comments.json", 'utf-8', function(err, data) {
    if (err) {
        throw err;
    }
    if (typeof data !== "undefined") {
        // Parse the current contents of the file into array
        var currentComments = JSON.parse(data);

        // Create our new comment
        var newComment = {
            "Username": usercommented,
            "ProjectID": project_id,
            "TimeStamp": time,
            "Comments": comment
        };

        // Push it onto the end of the existing comments
        currentComments.push(newComment);

        // Convert comments back to string to be written
        var stringifiedComments = JSON.stringify(currentComments);

        // Write back to file!
        fs.writeFile("comments.json", stringifiedComments, function (err) {
            console.log(err);
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM