我有需要循环的JSON数据。数据位于标题为" people.json"其结构如下:
[{"firstname":"John","lastname":"Smith","age":"40"},{"firstname":"Bill","lastname":"Jones","age":"40"}, ...]
我想读取此文件中的每个对象并保存(我使用Mongoose)。以下是我到目前为止的情况:
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) {});
}
});
我虽然无法让这个工作。我做错了什么?
答案 0 :(得分:30)
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) {});
}
});
答案 1 :(得分:10)
ES6 for..of
也可以这样做。
fs.readFile('./people.json', 'utf8', function (err,data) {
for(var item of data) {
console.log('item: ', [item.firstname, ...]);
}
});