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?
To loop through a JSON array with JavaScript, we can use a for of loop. to loop through the json array with a for of loop. We assign the entry being looped through to obj . Then we get the value of the id property of the object in the loop and log it.
1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.
Use Object. values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.
The outer forEach() loop is used to iterate through the objects array.
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) {});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With