1

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

4
  • Parse the JSON, alter the ids, and re-stringify it? Commented Jul 26, 2016 at 10:09
  • I would guess that fs is the module you are searching for when you wish to write to file. I bet googling "how to write to file nodejs" would give you a good clue on what to use ;P Commented Jul 26, 2016 at 10:09
  • Can you show us what you have attempted and where you have gone wrong. Specifically an example of your code. Commented Jul 26, 2016 at 10:21
  • @alexi2 updated , this is how i imagine it Commented Jul 26, 2016 at 11:47

2 Answers 2

1

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');
});
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks alot!! There is a small error with 'let' in for loop [ Block-scoped declarations <let, const, function, class> not yet supported ] so i changed it to var. Why have u used const instead of var ? And also it is somehow writes only IDs like so : [{"id":1},{"id":2},{"id":3},{"id":4}........
You can replace all the variable declarations with var if your version of javascript does not yet support that type of variable declaration. This is habit as I am coding in ES6. You can convert the id to a string inside the object function generator.
Made an edit to convert id to string, and to support your version of javascript.
Thanks once again ! This programming world , i learn something new everyday :) The problem was that i've wrote var jsonObj = '[ {} ]' instead of '{ }'. Now everything works!
I'm happy to help!
1

Depend from your needs. Use streams as one of the many solutions:

const fs = require('fs');

const PATH_TO_FILE = 'path/to/file';

let data = {
  id: null,
  value: 'some value'
};

let stream = fs.createWriteStream(PATH_TO_FILE);

//error handler
stream.on('error', function (error) {

});

for(let i = 1; i < 501; i++) {
  data.id = i;
  stream.write(JSON.stringify(data));
}

stream.end();

2 Comments

Thank ! Helped too !
Np. Streams are preferable if you need write big amount of data, in other case you'd better use writeFile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.