Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs append inside json file in array format

I want the nodejs to append all the data in the JSON format in following format

    [{
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   }, {
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   },{
      "name": "admin",
      "message": "dfd",
      "datetime": "2014-06-03 13:01:39"
   }]

And I want the nodejs to append more data. I m trying append but it's appending like this

{
  "name": "admin",
  "message": "dfd",
  "datetime": "2014-06-03 13:01:39"
}{
  "name": "admin",
  "message": "dfd",
  "datetime": "2014-06-03 13:01:39"
}

I m using the following code to append

    myData= { "name": "sam" , "message": "hi how are you", "datetime": "2014-5-1 4:4:4" };

    fs.appendFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
        if(err) {
          console.log(err);
        }
    });
like image 445
dave Avatar asked Jun 03 '14 09:06

dave


People also ask

How do I append JSON data in node JS?

To append json data/elements to a json file, read the file, parse the JSON, push the new result to the array, convert into a string, and save it.

How do I add a JSON to an array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.

How do I add to an existing JSON file?

To update a JSON object in a file, import the json library, read the file with json. load(file ), add the new entry to the list or dictionary data structure data , and write the updated JSON object with json. dump(data, file) .

Can you put an array in a JSON file?

In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.


1 Answers

JSON is not 'appendable' format. You have two options here:

  1. Read file, parse it, append data to array, serialize, replace file content.
  2. Switch to different file format. Actually CSV is good enough to store table-like data and is 'appendable'.
like image 79
Yury Tarabanko Avatar answered Oct 22 '22 11:10

Yury Tarabanko