在.json文件中添加另一个条目。的NodeJS

时间:2016-12-30 20:35:42

标签: javascript json node.js

我使用JSON文件存储一些数据,这是我目前的结构。 由我的代码尝试创建。

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))
})

我生成这样的JSON,而不是最好的代码,还在学习JS。

[]

我确实计划尽量减少它,它的代码太多太简单了,无论如何,它从jsongrid写入文件创建JSON,但唯一的问题是它们将它们写在彼此之上,如同如上所示,这不起作用,因为我无法通过名称或任何东西选择一个块,我尝试只读取文件,擦除它,向其添加[],然后将JSON写入文件再次,但这只会增加许多foo[1].Username,这也不起作用,我想访问JSON中的数据,例如Func</*input types here with ',' in between*/, /*output type here*/>。实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是在文件中存储一组JSON对象。

请记住,虽然JSON代表&#34; JavaScript Object Notation,&#34;数组也是有效的JSON。所以你的文件看起来像这样:

[
  {
    "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. "
  }
]

然后添加,删除,查找文件中的对象,读取整个文件,解析它,并做你需要的。

添加评论:

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