Kirill Vorobjov Kirill Vorobjov - 4 months ago 15
JSON Question

Copy json object with NodeJS loop into JSON file

Good day,

Is there a way to make a for loop in NodeJS and copy the same json object but with different 'id' into JSON file.

Lets say that i want to add 100 objects in this format :

[ { "id": 1, "Firstname": "Sven","Secondname": "Petersen","Age": "18" }]


when the server starts.

What would be the best way to make it ? What modules should i use ?

I thought i could do something like that :

for (var i = 0; i < 500; i++) {
fs.readFile("JSON/DB.json", "utf8", function () {
var data = '[{ "id": 1, "Firstname": "Sven", "Secondname": "Petersen", "Age": "18", }]'
var Data = JSON.parse(data);
var id = i;
for (var i = 0; i < Data; i++) {

};

var newData = JSON.stringify(Data);
fs.writeFile("JSON/DB.json", newData, "utf8");
})
};


P.S i'm a newb here

Answer

Edit: Convert id to string.

Try this

var fs = require('fs');

var jsonObj = '{ "id":"1","firstname": "Sven","secondname": "Petersen","age":"18" }'

var data = JSON.parse(jsonObj)
var newDataArray = []

function ObjectCreate (id, firstname, secondname, age) {
  this.id = id.toString();
  this.firstname = firstname;
  this.secondname = secondname;
  this.age = age;
}

for (var i = 1; i < 100; i++) {
  var obj = new ObjectCreate (i, data.firstname, data.secondname, data.age);
  newDataArray.push(obj);
}

var writeObject = JSON.stringify(newDataArray)

fs.writeFile('data.json', writeObject, function(err) {
  if(err) throw err;
  console.log('done');
});