Rebekah Rebekah - 7 days ago 6
Javascript Question

using faker to create a json file

I am trying to create a faker js file that will create a json file with 25 random user data.

First I start with an empty army, then open a for loop and place the faker inside, then push the data and print it to a json file but it doesn't seem to work.

Here is my code



var faker = require('faker');
var fs = require('fs');

var ourfaker = [];

for (i=0; i<=25; i++)

var data = {};
{
data.name = faker.fake("{{name.findName}}");
data.email = faker.fake("{{internet.email}}");

ourfaker.push(data);
};

fs.writeFile('data.json', JSON.stringify(data), (err) => {
if (err) throw err;
console.log('It\'s saved!');
});




Answer

Judiciously using brackets would help clarify what is going on here.

for (i=0; i<=25; i++)

var data = {};

Is defining data 25 times. You then have an empty block that adds your properties to data. What you really need to do is:

for (i=0; i<=25; i++) {
  var data = {};
  data.name = faker.fake("{{name.findName}}");
  data.email = faker.fake("{{internet.email}}");
  ourfaker.push(data);
}

Also, JSON.stringify(data) should be JSON.stringify(ourFaker)

Comments