write/add data in JSON file using node.js











up vote
103
down vote

favorite
27












I am trying to write JSON file using node from loop data
eg



var jsonfile = require('jsonfile');
for (i=0; i <11 ; i++){
jsonfile.writeFile('loop.json', "id :" + i + " square :" + i*i);
}


outPut in loop.json is



id :1 square : 1


but I want output file like this (below) and also if I run that code again it should add that new output as elements in same existing JSON file



{
"table": [
{
"Id ": 1,
"square ": 1
},
{
"Id ": 2,
"square ": 3
},
{
"Id ": 3,
"square ": 9
},
{
"Id ": 4,
"square ": 16
},
{
"Id ": 5,
"square ": 25
},
{
"Id ": 6,
"square ": 36
},
{
"Id ": 7,
"square ": 49
},
{
"Id ": 8,
"square ": 64
},
{
"Id ": 9,
"square ": 81
},
{
"Id ": 10,
"square ": 100
}
]
}


I want to use same file that I created 1st time but whenever I run that code new elements should add in that same file



var fs = require('fs');

var obj = {
table:
};

fs.exists('myjsonfile.json', function(exists){
if(exists){
console.log("yes file exists");
fs.readFile('myjsonfile.json', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data);
for (i=0; i<5 ; i++){
obj.table.push({id: i, square:i*i});
}
var json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json);
}});
} else {
console.log("file not exists")
for (i=0; i<5 ; i++){
obj.table.push({id: i, square:i*i});
}
var json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json);
}
});









share|improve this question




























    up vote
    103
    down vote

    favorite
    27












    I am trying to write JSON file using node from loop data
    eg



    var jsonfile = require('jsonfile');
    for (i=0; i <11 ; i++){
    jsonfile.writeFile('loop.json', "id :" + i + " square :" + i*i);
    }


    outPut in loop.json is



    id :1 square : 1


    but I want output file like this (below) and also if I run that code again it should add that new output as elements in same existing JSON file



    {
    "table": [
    {
    "Id ": 1,
    "square ": 1
    },
    {
    "Id ": 2,
    "square ": 3
    },
    {
    "Id ": 3,
    "square ": 9
    },
    {
    "Id ": 4,
    "square ": 16
    },
    {
    "Id ": 5,
    "square ": 25
    },
    {
    "Id ": 6,
    "square ": 36
    },
    {
    "Id ": 7,
    "square ": 49
    },
    {
    "Id ": 8,
    "square ": 64
    },
    {
    "Id ": 9,
    "square ": 81
    },
    {
    "Id ": 10,
    "square ": 100
    }
    ]
    }


    I want to use same file that I created 1st time but whenever I run that code new elements should add in that same file



    var fs = require('fs');

    var obj = {
    table:
    };

    fs.exists('myjsonfile.json', function(exists){
    if(exists){
    console.log("yes file exists");
    fs.readFile('myjsonfile.json', function readFileCallback(err, data){
    if (err){
    console.log(err);
    } else {
    obj = JSON.parse(data);
    for (i=0; i<5 ; i++){
    obj.table.push({id: i, square:i*i});
    }
    var json = JSON.stringify(obj);
    fs.writeFile('myjsonfile.json', json);
    }});
    } else {
    console.log("file not exists")
    for (i=0; i<5 ; i++){
    obj.table.push({id: i, square:i*i});
    }
    var json = JSON.stringify(obj);
    fs.writeFile('myjsonfile.json', json);
    }
    });









    share|improve this question


























      up vote
      103
      down vote

      favorite
      27









      up vote
      103
      down vote

      favorite
      27






      27





      I am trying to write JSON file using node from loop data
      eg



      var jsonfile = require('jsonfile');
      for (i=0; i <11 ; i++){
      jsonfile.writeFile('loop.json', "id :" + i + " square :" + i*i);
      }


      outPut in loop.json is



      id :1 square : 1


      but I want output file like this (below) and also if I run that code again it should add that new output as elements in same existing JSON file



      {
      "table": [
      {
      "Id ": 1,
      "square ": 1
      },
      {
      "Id ": 2,
      "square ": 3
      },
      {
      "Id ": 3,
      "square ": 9
      },
      {
      "Id ": 4,
      "square ": 16
      },
      {
      "Id ": 5,
      "square ": 25
      },
      {
      "Id ": 6,
      "square ": 36
      },
      {
      "Id ": 7,
      "square ": 49
      },
      {
      "Id ": 8,
      "square ": 64
      },
      {
      "Id ": 9,
      "square ": 81
      },
      {
      "Id ": 10,
      "square ": 100
      }
      ]
      }


      I want to use same file that I created 1st time but whenever I run that code new elements should add in that same file



      var fs = require('fs');

      var obj = {
      table:
      };

      fs.exists('myjsonfile.json', function(exists){
      if(exists){
      console.log("yes file exists");
      fs.readFile('myjsonfile.json', function readFileCallback(err, data){
      if (err){
      console.log(err);
      } else {
      obj = JSON.parse(data);
      for (i=0; i<5 ; i++){
      obj.table.push({id: i, square:i*i});
      }
      var json = JSON.stringify(obj);
      fs.writeFile('myjsonfile.json', json);
      }});
      } else {
      console.log("file not exists")
      for (i=0; i<5 ; i++){
      obj.table.push({id: i, square:i*i});
      }
      var json = JSON.stringify(obj);
      fs.writeFile('myjsonfile.json', json);
      }
      });









      share|improve this question















      I am trying to write JSON file using node from loop data
      eg



      var jsonfile = require('jsonfile');
      for (i=0; i <11 ; i++){
      jsonfile.writeFile('loop.json', "id :" + i + " square :" + i*i);
      }


      outPut in loop.json is



      id :1 square : 1


      but I want output file like this (below) and also if I run that code again it should add that new output as elements in same existing JSON file



      {
      "table": [
      {
      "Id ": 1,
      "square ": 1
      },
      {
      "Id ": 2,
      "square ": 3
      },
      {
      "Id ": 3,
      "square ": 9
      },
      {
      "Id ": 4,
      "square ": 16
      },
      {
      "Id ": 5,
      "square ": 25
      },
      {
      "Id ": 6,
      "square ": 36
      },
      {
      "Id ": 7,
      "square ": 49
      },
      {
      "Id ": 8,
      "square ": 64
      },
      {
      "Id ": 9,
      "square ": 81
      },
      {
      "Id ": 10,
      "square ": 100
      }
      ]
      }


      I want to use same file that I created 1st time but whenever I run that code new elements should add in that same file



      var fs = require('fs');

      var obj = {
      table:
      };

      fs.exists('myjsonfile.json', function(exists){
      if(exists){
      console.log("yes file exists");
      fs.readFile('myjsonfile.json', function readFileCallback(err, data){
      if (err){
      console.log(err);
      } else {
      obj = JSON.parse(data);
      for (i=0; i<5 ; i++){
      obj.table.push({id: i, square:i*i});
      }
      var json = JSON.stringify(obj);
      fs.writeFile('myjsonfile.json', json);
      }});
      } else {
      console.log("file not exists")
      for (i=0; i<5 ; i++){
      obj.table.push({id: i, square:i*i});
      }
      var json = JSON.stringify(obj);
      fs.writeFile('myjsonfile.json', json);
      }
      });






      javascript json node.js fs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 11 '16 at 22:00









      Philip Kirkbride

      7,6632682148




      7,6632682148










      asked Apr 26 '16 at 5:48









      Isoftmaster

      523259




      523259
























          6 Answers
          6






          active

          oldest

          votes

















          up vote
          218
          down vote



          accepted










          If this json file won't become too big over the time you should try:





          1. Create a javascript object with the table array in it



            var obj = {
            table:
            };



          2. Add some data to it like



            obj.table.push({id: 1, square:2});



          3. Convert it from an object to string with stringify



            var json = JSON.stringify(obj);



          4. use fs to write the file to disk



            var fs = require('fs');
            fs.writeFile('myjsonfile.json', json, 'utf8', callback);



          5. if you want to append it read the json file and convert it back to an object



            fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
            if (err){
            console.log(err);
            } else {
            obj = JSON.parse(data); //now it an object
            obj.table.push({id: 2, square:3}); //add some data
            json = JSON.stringify(obj); //convert it back to json
            fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
            }});



          This will work for data big as 100 MB max effectively. Over this limit, you should use a database engine.



          UPDATE:



          Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback).
          With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.






          share|improve this answer



















          • 1




            thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
            – Isoftmaster
            Apr 26 '16 at 17:57








          • 1




            Updated my answer according to your new question
            – kailniris
            Apr 26 '16 at 18:44






          • 1




            thank you once again i made my code working :D with all your support but i used fs.exists function my question updated with answer
            – Isoftmaster
            Apr 26 '16 at 18:51


















          up vote
          9
          down vote













          Please try the following program. You might be expecting this output.



          var fs = require('fs');

          var data = {}
          data.table =
          for (i=0; i <26 ; i++){
          var obj = {
          id: i,
          square: i * i
          }
          data.table.push(obj)
          }
          fs.writeFile ("input.json", JSON.stringify(data), function(err) {
          if (err) throw err;
          console.log('complete');
          }
          );


          Save this program in a javascript file, say, square.js.



          Then run the program from command prompt using the command node square.js



          What it does is, simply overwriting the existing file with new set of data, every time you execute the command.



          Happy Coding.






          share|improve this answer




























            up vote
            5
            down vote













            you should read the file, every time you want to add a new property to the json, and then add the the new properties



            var fs = require('fs');
            fs.readFile('data.json',function(err,content){
            if(err) throw err;
            var parseJson = JSON.parse(content);
            for (i=0; i <11 ; i++){
            parseJson.table.push({id:i, square:i*i})
            }
            fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
            if(err) throw err;
            })
            })





            share|improve this answer

















            • 1




              thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct to create new file i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
              – Isoftmaster
              Apr 26 '16 at 18:00


















            up vote
            3
            down vote













            For formatting jsonfile gives spaces option which you can pass as a parameter:



               jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
            console.error(err);
            })


            Or use jsonfile.spaces = 4. Read details here.



            I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.



            var jsonfile = require('jsonfile');
            var obj={
            'table':
            };

            for (i=0; i <11 ; i++){
            obj.table.push({"id":i,"square":i*i});
            }
            jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
            console.log(err);
            });





            share|improve this answer






























              up vote
              1
              down vote













              Above example is also correct, but i provide simple example:



              var fs = require("fs");
              var sampleObject = {
              name: 'pankaj',
              member: 'stack',
              type: {
              x: 11,
              y: 22
              }
              };

              fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
              if (err) {
              console.error(err);
              return;
              };
              console.log("File has been created");
              });





              share|improve this answer




























                up vote
                0
                down vote













                One could simply log the JavaScript variable to the console in fx. Firefox, right-click and select copy object, then paste in to a text editor fx. Notepad++ and save it locally on your computer as .json file.



                 let data = [{ Id : 1, square : 1 }, { Id : 2, square : 3 }, ...];
                console.log(users);





                share|improve this answer





















                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                   

                  draft saved


                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36856232%2fwrite-add-data-in-json-file-using-node-js%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes








                  up vote
                  218
                  down vote



                  accepted










                  If this json file won't become too big over the time you should try:





                  1. Create a javascript object with the table array in it



                    var obj = {
                    table:
                    };



                  2. Add some data to it like



                    obj.table.push({id: 1, square:2});



                  3. Convert it from an object to string with stringify



                    var json = JSON.stringify(obj);



                  4. use fs to write the file to disk



                    var fs = require('fs');
                    fs.writeFile('myjsonfile.json', json, 'utf8', callback);



                  5. if you want to append it read the json file and convert it back to an object



                    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
                    if (err){
                    console.log(err);
                    } else {
                    obj = JSON.parse(data); //now it an object
                    obj.table.push({id: 2, square:3}); //add some data
                    json = JSON.stringify(obj); //convert it back to json
                    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
                    }});



                  This will work for data big as 100 MB max effectively. Over this limit, you should use a database engine.



                  UPDATE:



                  Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback).
                  With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.






                  share|improve this answer



















                  • 1




                    thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                    – Isoftmaster
                    Apr 26 '16 at 17:57








                  • 1




                    Updated my answer according to your new question
                    – kailniris
                    Apr 26 '16 at 18:44






                  • 1




                    thank you once again i made my code working :D with all your support but i used fs.exists function my question updated with answer
                    – Isoftmaster
                    Apr 26 '16 at 18:51















                  up vote
                  218
                  down vote



                  accepted










                  If this json file won't become too big over the time you should try:





                  1. Create a javascript object with the table array in it



                    var obj = {
                    table:
                    };



                  2. Add some data to it like



                    obj.table.push({id: 1, square:2});



                  3. Convert it from an object to string with stringify



                    var json = JSON.stringify(obj);



                  4. use fs to write the file to disk



                    var fs = require('fs');
                    fs.writeFile('myjsonfile.json', json, 'utf8', callback);



                  5. if you want to append it read the json file and convert it back to an object



                    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
                    if (err){
                    console.log(err);
                    } else {
                    obj = JSON.parse(data); //now it an object
                    obj.table.push({id: 2, square:3}); //add some data
                    json = JSON.stringify(obj); //convert it back to json
                    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
                    }});



                  This will work for data big as 100 MB max effectively. Over this limit, you should use a database engine.



                  UPDATE:



                  Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback).
                  With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.






                  share|improve this answer



















                  • 1




                    thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                    – Isoftmaster
                    Apr 26 '16 at 17:57








                  • 1




                    Updated my answer according to your new question
                    – kailniris
                    Apr 26 '16 at 18:44






                  • 1




                    thank you once again i made my code working :D with all your support but i used fs.exists function my question updated with answer
                    – Isoftmaster
                    Apr 26 '16 at 18:51













                  up vote
                  218
                  down vote



                  accepted







                  up vote
                  218
                  down vote



                  accepted






                  If this json file won't become too big over the time you should try:





                  1. Create a javascript object with the table array in it



                    var obj = {
                    table:
                    };



                  2. Add some data to it like



                    obj.table.push({id: 1, square:2});



                  3. Convert it from an object to string with stringify



                    var json = JSON.stringify(obj);



                  4. use fs to write the file to disk



                    var fs = require('fs');
                    fs.writeFile('myjsonfile.json', json, 'utf8', callback);



                  5. if you want to append it read the json file and convert it back to an object



                    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
                    if (err){
                    console.log(err);
                    } else {
                    obj = JSON.parse(data); //now it an object
                    obj.table.push({id: 2, square:3}); //add some data
                    json = JSON.stringify(obj); //convert it back to json
                    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
                    }});



                  This will work for data big as 100 MB max effectively. Over this limit, you should use a database engine.



                  UPDATE:



                  Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback).
                  With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.






                  share|improve this answer














                  If this json file won't become too big over the time you should try:





                  1. Create a javascript object with the table array in it



                    var obj = {
                    table:
                    };



                  2. Add some data to it like



                    obj.table.push({id: 1, square:2});



                  3. Convert it from an object to string with stringify



                    var json = JSON.stringify(obj);



                  4. use fs to write the file to disk



                    var fs = require('fs');
                    fs.writeFile('myjsonfile.json', json, 'utf8', callback);



                  5. if you want to append it read the json file and convert it back to an object



                    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
                    if (err){
                    console.log(err);
                    } else {
                    obj = JSON.parse(data); //now it an object
                    obj.table.push({id: 2, square:3}); //add some data
                    json = JSON.stringify(obj); //convert it back to json
                    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
                    }});



                  This will work for data big as 100 MB max effectively. Over this limit, you should use a database engine.



                  UPDATE:



                  Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback).
                  With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 31 at 16:08









                  geizio

                  48112




                  48112










                  answered Apr 26 '16 at 6:23









                  kailniris

                  3,2851917




                  3,2851917








                  • 1




                    thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                    – Isoftmaster
                    Apr 26 '16 at 17:57








                  • 1




                    Updated my answer according to your new question
                    – kailniris
                    Apr 26 '16 at 18:44






                  • 1




                    thank you once again i made my code working :D with all your support but i used fs.exists function my question updated with answer
                    – Isoftmaster
                    Apr 26 '16 at 18:51














                  • 1




                    thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                    – Isoftmaster
                    Apr 26 '16 at 17:57








                  • 1




                    Updated my answer according to your new question
                    – kailniris
                    Apr 26 '16 at 18:44






                  • 1




                    thank you once again i made my code working :D with all your support but i used fs.exists function my question updated with answer
                    – Isoftmaster
                    Apr 26 '16 at 18:51








                  1




                  1




                  thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                  – Isoftmaster
                  Apr 26 '16 at 17:57






                  thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                  – Isoftmaster
                  Apr 26 '16 at 17:57






                  1




                  1




                  Updated my answer according to your new question
                  – kailniris
                  Apr 26 '16 at 18:44




                  Updated my answer according to your new question
                  – kailniris
                  Apr 26 '16 at 18:44




                  1




                  1




                  thank you once again i made my code working :D with all your support but i used fs.exists function my question updated with answer
                  – Isoftmaster
                  Apr 26 '16 at 18:51




                  thank you once again i made my code working :D with all your support but i used fs.exists function my question updated with answer
                  – Isoftmaster
                  Apr 26 '16 at 18:51












                  up vote
                  9
                  down vote













                  Please try the following program. You might be expecting this output.



                  var fs = require('fs');

                  var data = {}
                  data.table =
                  for (i=0; i <26 ; i++){
                  var obj = {
                  id: i,
                  square: i * i
                  }
                  data.table.push(obj)
                  }
                  fs.writeFile ("input.json", JSON.stringify(data), function(err) {
                  if (err) throw err;
                  console.log('complete');
                  }
                  );


                  Save this program in a javascript file, say, square.js.



                  Then run the program from command prompt using the command node square.js



                  What it does is, simply overwriting the existing file with new set of data, every time you execute the command.



                  Happy Coding.






                  share|improve this answer

























                    up vote
                    9
                    down vote













                    Please try the following program. You might be expecting this output.



                    var fs = require('fs');

                    var data = {}
                    data.table =
                    for (i=0; i <26 ; i++){
                    var obj = {
                    id: i,
                    square: i * i
                    }
                    data.table.push(obj)
                    }
                    fs.writeFile ("input.json", JSON.stringify(data), function(err) {
                    if (err) throw err;
                    console.log('complete');
                    }
                    );


                    Save this program in a javascript file, say, square.js.



                    Then run the program from command prompt using the command node square.js



                    What it does is, simply overwriting the existing file with new set of data, every time you execute the command.



                    Happy Coding.






                    share|improve this answer























                      up vote
                      9
                      down vote










                      up vote
                      9
                      down vote









                      Please try the following program. You might be expecting this output.



                      var fs = require('fs');

                      var data = {}
                      data.table =
                      for (i=0; i <26 ; i++){
                      var obj = {
                      id: i,
                      square: i * i
                      }
                      data.table.push(obj)
                      }
                      fs.writeFile ("input.json", JSON.stringify(data), function(err) {
                      if (err) throw err;
                      console.log('complete');
                      }
                      );


                      Save this program in a javascript file, say, square.js.



                      Then run the program from command prompt using the command node square.js



                      What it does is, simply overwriting the existing file with new set of data, every time you execute the command.



                      Happy Coding.






                      share|improve this answer












                      Please try the following program. You might be expecting this output.



                      var fs = require('fs');

                      var data = {}
                      data.table =
                      for (i=0; i <26 ; i++){
                      var obj = {
                      id: i,
                      square: i * i
                      }
                      data.table.push(obj)
                      }
                      fs.writeFile ("input.json", JSON.stringify(data), function(err) {
                      if (err) throw err;
                      console.log('complete');
                      }
                      );


                      Save this program in a javascript file, say, square.js.



                      Then run the program from command prompt using the command node square.js



                      What it does is, simply overwriting the existing file with new set of data, every time you execute the command.



                      Happy Coding.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Apr 26 '16 at 6:15









                      Jacob Nelson

                      456415




                      456415






















                          up vote
                          5
                          down vote













                          you should read the file, every time you want to add a new property to the json, and then add the the new properties



                          var fs = require('fs');
                          fs.readFile('data.json',function(err,content){
                          if(err) throw err;
                          var parseJson = JSON.parse(content);
                          for (i=0; i <11 ; i++){
                          parseJson.table.push({id:i, square:i*i})
                          }
                          fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
                          if(err) throw err;
                          })
                          })





                          share|improve this answer

















                          • 1




                            thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct to create new file i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                            – Isoftmaster
                            Apr 26 '16 at 18:00















                          up vote
                          5
                          down vote













                          you should read the file, every time you want to add a new property to the json, and then add the the new properties



                          var fs = require('fs');
                          fs.readFile('data.json',function(err,content){
                          if(err) throw err;
                          var parseJson = JSON.parse(content);
                          for (i=0; i <11 ; i++){
                          parseJson.table.push({id:i, square:i*i})
                          }
                          fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
                          if(err) throw err;
                          })
                          })





                          share|improve this answer

















                          • 1




                            thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct to create new file i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                            – Isoftmaster
                            Apr 26 '16 at 18:00













                          up vote
                          5
                          down vote










                          up vote
                          5
                          down vote









                          you should read the file, every time you want to add a new property to the json, and then add the the new properties



                          var fs = require('fs');
                          fs.readFile('data.json',function(err,content){
                          if(err) throw err;
                          var parseJson = JSON.parse(content);
                          for (i=0; i <11 ; i++){
                          parseJson.table.push({id:i, square:i*i})
                          }
                          fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
                          if(err) throw err;
                          })
                          })





                          share|improve this answer












                          you should read the file, every time you want to add a new property to the json, and then add the the new properties



                          var fs = require('fs');
                          fs.readFile('data.json',function(err,content){
                          if(err) throw err;
                          var parseJson = JSON.parse(content);
                          for (i=0; i <11 ; i++){
                          parseJson.table.push({id:i, square:i*i})
                          }
                          fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
                          if(err) throw err;
                          })
                          })






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Apr 26 '16 at 6:13









                          Zamboney

                          1,496619




                          1,496619








                          • 1




                            thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct to create new file i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                            – Isoftmaster
                            Apr 26 '16 at 18:00














                          • 1




                            thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct to create new file i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                            – Isoftmaster
                            Apr 26 '16 at 18:00








                          1




                          1




                          thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct to create new file i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                          – Isoftmaster
                          Apr 26 '16 at 18:00




                          thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct to create new file i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run
                          – Isoftmaster
                          Apr 26 '16 at 18:00










                          up vote
                          3
                          down vote













                          For formatting jsonfile gives spaces option which you can pass as a parameter:



                             jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
                          console.error(err);
                          })


                          Or use jsonfile.spaces = 4. Read details here.



                          I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.



                          var jsonfile = require('jsonfile');
                          var obj={
                          'table':
                          };

                          for (i=0; i <11 ; i++){
                          obj.table.push({"id":i,"square":i*i});
                          }
                          jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
                          console.log(err);
                          });





                          share|improve this answer



























                            up vote
                            3
                            down vote













                            For formatting jsonfile gives spaces option which you can pass as a parameter:



                               jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
                            console.error(err);
                            })


                            Or use jsonfile.spaces = 4. Read details here.



                            I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.



                            var jsonfile = require('jsonfile');
                            var obj={
                            'table':
                            };

                            for (i=0; i <11 ; i++){
                            obj.table.push({"id":i,"square":i*i});
                            }
                            jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
                            console.log(err);
                            });





                            share|improve this answer

























                              up vote
                              3
                              down vote










                              up vote
                              3
                              down vote









                              For formatting jsonfile gives spaces option which you can pass as a parameter:



                                 jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
                              console.error(err);
                              })


                              Or use jsonfile.spaces = 4. Read details here.



                              I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.



                              var jsonfile = require('jsonfile');
                              var obj={
                              'table':
                              };

                              for (i=0; i <11 ; i++){
                              obj.table.push({"id":i,"square":i*i});
                              }
                              jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
                              console.log(err);
                              });





                              share|improve this answer














                              For formatting jsonfile gives spaces option which you can pass as a parameter:



                                 jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
                              console.error(err);
                              })


                              Or use jsonfile.spaces = 4. Read details here.



                              I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.



                              var jsonfile = require('jsonfile');
                              var obj={
                              'table':
                              };

                              for (i=0; i <11 ; i++){
                              obj.table.push({"id":i,"square":i*i});
                              }
                              jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
                              console.log(err);
                              });






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Apr 26 '16 at 6:45

























                              answered Apr 26 '16 at 6:40









                              avck

                              1,74311530




                              1,74311530






















                                  up vote
                                  1
                                  down vote













                                  Above example is also correct, but i provide simple example:



                                  var fs = require("fs");
                                  var sampleObject = {
                                  name: 'pankaj',
                                  member: 'stack',
                                  type: {
                                  x: 11,
                                  y: 22
                                  }
                                  };

                                  fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
                                  if (err) {
                                  console.error(err);
                                  return;
                                  };
                                  console.log("File has been created");
                                  });





                                  share|improve this answer

























                                    up vote
                                    1
                                    down vote













                                    Above example is also correct, but i provide simple example:



                                    var fs = require("fs");
                                    var sampleObject = {
                                    name: 'pankaj',
                                    member: 'stack',
                                    type: {
                                    x: 11,
                                    y: 22
                                    }
                                    };

                                    fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
                                    if (err) {
                                    console.error(err);
                                    return;
                                    };
                                    console.log("File has been created");
                                    });





                                    share|improve this answer























                                      up vote
                                      1
                                      down vote










                                      up vote
                                      1
                                      down vote









                                      Above example is also correct, but i provide simple example:



                                      var fs = require("fs");
                                      var sampleObject = {
                                      name: 'pankaj',
                                      member: 'stack',
                                      type: {
                                      x: 11,
                                      y: 22
                                      }
                                      };

                                      fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
                                      if (err) {
                                      console.error(err);
                                      return;
                                      };
                                      console.log("File has been created");
                                      });





                                      share|improve this answer












                                      Above example is also correct, but i provide simple example:



                                      var fs = require("fs");
                                      var sampleObject = {
                                      name: 'pankaj',
                                      member: 'stack',
                                      type: {
                                      x: 11,
                                      y: 22
                                      }
                                      };

                                      fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
                                      if (err) {
                                      console.error(err);
                                      return;
                                      };
                                      console.log("File has been created");
                                      });






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Aug 13 at 11:31









                                      Pankaj Chauhan

                                      39747




                                      39747






















                                          up vote
                                          0
                                          down vote













                                          One could simply log the JavaScript variable to the console in fx. Firefox, right-click and select copy object, then paste in to a text editor fx. Notepad++ and save it locally on your computer as .json file.



                                           let data = [{ Id : 1, square : 1 }, { Id : 2, square : 3 }, ...];
                                          console.log(users);





                                          share|improve this answer

























                                            up vote
                                            0
                                            down vote













                                            One could simply log the JavaScript variable to the console in fx. Firefox, right-click and select copy object, then paste in to a text editor fx. Notepad++ and save it locally on your computer as .json file.



                                             let data = [{ Id : 1, square : 1 }, { Id : 2, square : 3 }, ...];
                                            console.log(users);





                                            share|improve this answer























                                              up vote
                                              0
                                              down vote










                                              up vote
                                              0
                                              down vote









                                              One could simply log the JavaScript variable to the console in fx. Firefox, right-click and select copy object, then paste in to a text editor fx. Notepad++ and save it locally on your computer as .json file.



                                               let data = [{ Id : 1, square : 1 }, { Id : 2, square : 3 }, ...];
                                              console.log(users);





                                              share|improve this answer












                                              One could simply log the JavaScript variable to the console in fx. Firefox, right-click and select copy object, then paste in to a text editor fx. Notepad++ and save it locally on your computer as .json file.



                                               let data = [{ Id : 1, square : 1 }, { Id : 2, square : 3 }, ...];
                                              console.log(users);






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Nov 21 at 11:13









                                              chri3g91

                                              666




                                              666






























                                                   

                                                  draft saved


                                                  draft discarded



















































                                                   


                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f36856232%2fwrite-add-data-in-json-file-using-node-js%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Lallio

                                                  Futebolista

                                                  Jornalista