3

I was wondering if there is a way to set up a fake data (information) such as a name and email and have it stored in a JSON file.

I known faker can be used with node and NPM to create fake data in JS but what about with JSON?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Rebekah
  • 57
  • 1
  • 2
  • 11

2 Answers2

1

One more example generates ten users and writes them to a data.json file.

employees.js

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

function generateEmployees() {
  let employees = [];
  for (let id = 1; id <= 10; id++) {
    let firstName = faker.name.firstName();
    let lastName = faker.name.lastName();
    let email = faker.internet.email();
    employees.push({
      id: id,
      first_name: firstName,
      last_name: lastName,
      email: email,
    });
  }
  return { employees: employees };
}
module.exports = generateEmployees;

let dataObj = generateEmployees();
fs.writeFileSync('data.json', JSON.stringify(dataObj, null, '\t'));

Serving fake data with JSON Server

$ json-server employees.js

enter image description here

Now you can click on the Resources link to see the result.


Update

Inspired by @le_m, you can generate dummy data without using a for loop:

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

const generateEmployee = () => {
  return {
    id: faker.random.uuid(),
    first_name: faker.name.firstName(),
    last_name: faker.name.lastName(),
    email: faker.internet.email(),
  };
};

const generateEmployees = (numUsers) => {
  return Array.from({ length: numUsers }, generateEmployee);
};

let dataObj = generateEmployees(10);
fs.writeFileSync('data.json', JSON.stringify(dataObj, null, '\t'));

Then, simply start your server using the following command:

$ node employees.js
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
0
var faker = require('faker');
var fs = require('fs');

var data = {};

data.name = faker.name.findName();
data.email = faker.internet.email();

fs.writeFile('data.json', JSON.stringify(data), (err) => {
  if (err) throw err;
  console.log('It\'s saved!');
});
ksav
  • 20,015
  • 6
  • 46
  • 66
  • this saves the file as a json file but not in json format :-( – Rebekah Nov 24 '16 at 12:30
  • is there a way to set it so that I would be able to say add 10 new user records to the json file – Rebekah Nov 24 '16 at 15:02
  • Sure, there is a way. Start with an empty results array and generate the faker data inside a loop. Push to the results array each time. Then when the loop is finished, write the stringified results to your file. – ksav Nov 24 '16 at 15:34
  • Thank you, this really helped – Rebekah Nov 24 '16 at 15:46
  • Good luck. Also, check out this question for pushing to an array from a loop. http://stackoverflow.com/questions/12491101/javascript-create-array-from-for-loop – ksav Nov 24 '16 at 15:49