2016-12-30 4 views
0

Ich verwende eine JSON-Datei, um einige Daten zu speichern, das ist meine aktuelle Struktur. erstellt von meinem Code versucht.Hinzufügen eines weiteren Eintrags zu einer .json-Datei. 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. " 
} 

Ich erzeuge die JSON wie diese, nicht der beste Code, immer noch lernen 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)) 
}) 

Ich plane es ein wenig zu minimieren, seine zu viel Code für etwas so einfach, jeder Art und Weise, schafft es die JSON aus der jsongrid zu Datei schreibt, aber das einzige Problem ist, schreibt sie auf der Spitze wie oben gezeigt funktioniert das nicht, weil ich keinen Block mit Namen oder was auch immer herausbekommen kann. Ich habe gerade versucht, die Datei zu lesen, sie zu löschen, die [] hinzuzufügen und dann den JSON in die Datei zu schreiben wieder, aber das fügt einfach viele [] um, die auch nicht funktioniert, wollte ich auf die Daten in der JSON wie, foo[1].Username zum Beispiel zugreifen. Was ist der beste Weg, dies zu erreichen?

+0

behandeln es nicht als String: die alte analysieren, ändern Sie das Objekt/Array, dann serialisiert und alle als eine speichern. – dandavis

Antwort

1

Die einfachste Lösung besteht darin, ein Array von JSON-Objekten in Ihrer Datei zu speichern.

Beachten Sie, dass, obwohl JSON für "JavaScript Object Notation" steht, ein Array auch JSON ist. So Ihre Datei könnte wie folgt aussehen:

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

Dann hinzuzufügen, zu entfernen, Lookup-Objekte in der Datei, lesen Sie die gesamte Datei in, analysieren sie, und tun, was Sie brauchen.

Hinzufügen Kommentar:

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

Haben einen SyntaxError: Unerwartetes Ende der Eingabe – Tom

+0

nach dem Entfernen der alten defekten Inhalt der .json-Datei und Ersetzen durch Ihr Beispiel, es funktionierte. – Tom

+0

Was wäre eine gute Möglichkeit, alle Daten in dieser JSON-Datei zu lesen? Ich dachte daran, eine Schleife zu verwenden und die Array-Zerstörung zu inkrementieren. – Tom

Verwandte Themen