Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  102] [ 5]  / answers: 1 / hits: 88346  / 6 Years ago, sun, march 25, 2018, 12:00:00

How can I fetch a local JSON file that is in my directory?



the JSON file looks like this:



[
{
name: Sara,
id: 3232
},
{
name: Jim,
id: 2342
},
{
name: Pete,
id: 532532
}
]


If I have the json information inside the same file I'm trying to use it, it works beautifully, but if I want to bring it in, I can't for the life of me get it to work and it keeps reading it as undefined.



here is what I have



getData() {


var json_data = require('../services/contributors.JSON');


for (var i in json_data){
console.log('Name: ' + json_data[i][name])

}


}


Can you see what I'm doing wrong? I'm trying to get this into react so maybe react works differently? I don't know. Any help will be appreciated. Thank you!


More From » json

 Answers
23

Try to use file system. Don't think reading from a JSON file works like that.



const fs = require('fs');
const json_data = require('../services/contributors.JSON');

fs.readFile(json_data, 'utf8', function (err, data) {
try {
data = JSON.parse(data)
for (let i in data){
console.log('Name:',data[i].name)
}
} catch (e) {
// Catch error in case file doesn't exist or isn't valid JSON
}
});

[#54860] Wednesday, March 21, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julissaimana

Total Points: 593
Total Questions: 108
Total Answers: 112

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
julissaimana questions
Thu, Jun 11, 20, 00:00, 4 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Thu, Mar 26, 20, 00:00, 4 Years ago
;