[javascript] Write / add data in JSON file using Node.js

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

This question is related to javascript json node.js fs

The answer is


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

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

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

        })
        
        
    });


  

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.


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

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

For synchronous approach

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to fs

Writing JSON object to a JSON file with fs.writeFileSync Using filesystem in node.js with async / await Write / add data in JSON file using Node.js Node.js Write a line into a .txt file NodeJS accessing file with relative path How to create full path with node's fs.mkdirSync? Read file from aws s3 bucket using node fs How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? nodejs get file name from absolute path? Node.js check if file exists