gpt4 book ai didi

json - 如何循环遍历 JSON 对象数组?

转载 作者:IT老高 更新时间:2023-10-28 13:09:37 27 4
gpt4 key购买 nike

我有需要循环的 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) {});
}
});

我无法让它工作。我做错了什么?

最佳答案

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) {});
}
});

关于json - 如何循环遍历 JSON 对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23117752/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com