Write / add data in JSON file using Node.js

JavascriptJsonnode.jsFs

Javascript Problem Overview


I am trying to write JSON file using node from loop data, e.g.:

let 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

const fs = require('fs');

let 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
                    });
                }

                let 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
            });
        }

        let json = JSON.stringify(obj);
        fs.writeFile('myjsonfile.json', json);
    }
});

Javascript Solutions


Solution 1 - Javascript

If this JSON file won't become too big over time, you should try:

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

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.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 that is up to 100 MB 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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

try

var fs = require("fs");
var sampleObject = { your data };

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

Solution 4 - Javascript

For synchronous approach

const fs = require('fs')
fs.writeFileSync('file.json', JSON.stringify(jsonVariable));

Solution 5 - Javascript

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;
  })
})

Solution 6 - Javascript

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");
});

Solution 7 - Javascript

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);
});

Solution 8 - Javascript

I agree with above answers, Here is a complete read and write sample for anyone who needs it.

     router.post('/', function(req, res, next) {

        console.log(req.body);
        var id = Math.floor((Math.random()*100)+1);

        var tital = req.body.title;
        var description = req.body.description;
        var mynotes = {"Id": id, "Title":tital, "Description": description};
        
        fs.readFile('db.json','utf8', function(err,data){
            var obj = JSON.parse(data);
            obj.push(mynotes);
            var strNotes = JSON.stringify(obj);
            fs.writeFile('db.json',strNotes, function(err){
                if(err) return console.log(err);
                console.log('Note added');
            });

        })
        
        
    });


  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIsoftmasterView Question on Stackoverflow
Solution 1 - JavascriptkailnirisView Answer on Stackoverflow
Solution 2 - JavascriptJacob NelsonView Answer on Stackoverflow
Solution 3 - Javascriptuser11426503View Answer on Stackoverflow
Solution 4 - JavascriptNirojan SelvanathanView Answer on Stackoverflow
Solution 5 - JavascriptZamboneyView Answer on Stackoverflow
Solution 6 - JavascriptPankaj ChauhanView Answer on Stackoverflow
Solution 7 - JavascriptavckView Answer on Stackoverflow
Solution 8 - JavascriptMJ XView Answer on Stackoverflow