0

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?

1
  • don't treat it as a string: parse the old, modify the object/array, then serialize and save all as one. Commented Dec 30, 2016 at 20:56

1 Answer 1

1

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);
        });
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Got a SyntaxError: Unexpected end of input
after removing the old broken contents of the .json file and replacing it with your example, it worked.
what would be a good way to read all the data inside that json file? I was thinking of using a loop, and incrementing the array destruction.
Not sure what you mean. The entire contents of the file will be in currentComments at line 12 in my example. That will contain the entire array in the file :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.