2016-12-30 6 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)) 
}) 

私は、それをとても簡単なもののために少し、そのあまりにも多くのコードを最小限にどのような方法を計画ん、それはjsongridからJSONを作成し、ファイルに書き込みますが、唯一の問題は、それがの上にそれらを書き込んでお互いに、上に示したように、私は名前でブロックを選ぶことができないので、これは機能しません。ファイルを読み込み、消去して、それに[]を追加してJSONをファイルに書き出しました再び、それはちょうど[]の周りをたくさん追加します。どちらもうまくいきません。私は、例えば、foo[1].UsernameのようなJSONのデータにアクセスしたかったのです。これを達成する最善の方法は何ですか?

+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

関連する問題