14

I have JSON data that I need to loop through. The data is in a file titled "people.json" that is structured as listed below:

[{"firstname":"John","lastname":"Smith","age":"40"},{"firstname":"Bill","lastname":"Jones","age":"40"}, ...]

I want to read each object in this file and save it (I'm using Mongoose). Here is what I have so far:

var fs = require('fs');
var Person = require('../models/people');

fs.readFile('./people.json', 'utf8', function (err,data) {
    var i;
    for(i = 0; i < data.length; i++) {
        var newPerson = new Person();
        newPerson.firstname = data[i].firstname;
        newPerson.lastname = data[i].lastname;
        newPerson.age = data[i].age;
        newPerson.save(function (err) {});
    }
});

I'm unable to get this to work though. What am I doing wrong?

2
  • The loop looks fine. Have you verified that there is no error and that you are actually getting data in your callback? Commented Apr 16, 2014 at 18:52
  • You might want to check out mongoimport, which would be a better way to do this. Commented Apr 16, 2014 at 18:53

3 Answers 3

33
fs.readFile('./people.json', 'utf8', function (err,data) {
  data = JSON.parse(data); // you missed that...
  for(var i = 0; i < data.length; i++) {
    var newPerson = new Person();
    newPerson.firstname = data[i].firstname;
    newPerson.lastname = data[i].lastname;
    newPerson.age = data[i].age;
    newPerson.save(function (err) {});
  }
});
Sign up to request clarification or add additional context in comments.

Comments

12

ES6 for..of can do that too.

fs.readFile('./people.json', 'utf8', function (err,data) {
  for(var item of data) {
     console.log('item: ', [item.firstname, ...]);
  }
});

Comments

0
const parsedData = JSON.parse(JSON.stringify(data));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.