2016-12-30 72 views
0

我正在使用JSON文件来存储一些数据,这是我目前的结构。由我的代码尝试创建的 。将另一个条目添加到.json文件。 NodeJS

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

我生成这样的JSON,而不是最好的代码,仍然学习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)) 
}) 

我打算通过最大限度地减少了一点,它的东西那么简单,任何方式太多的代码,它创建的JSON从jsongrid写入文件,但唯一的问题是它的顶部写他们彼此,如上所示,这不起作用,因为我无法通过名称或以往任何方式挑选出一个块,我试着只是读取文件,擦除它,将[]添加到它,然后将JSON写入文件但是这只是增加了大量的[],这也不起作用,我想访问JSON中的数据,例如foo[1].Username。达到这个目标的最好方法是什么?

+0

千万不要把它作为一个字符串:解析的时候,修改对象/数组,然后序列化和保存所有为一体。 – dandavis

回答

1

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

请记住,虽然JSON代表“JavaScript Object Notation”,但数组也是有效的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); 
     }); 
    } 
} 
+0

得到一个SyntaxError:输入 – Tom

+0

意外结束后,删除.json文件的旧损坏的内容并将其替换为您的示例,它的工作。 – Tom

+0

什么是读取该json文件中所有数据的好方法?我正在考虑使用循环,并增加数组销毁。 – Tom

相关问题