Reputation: 1008
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!
Upvotes: 22
Views: 116936
Reputation: 3913
With ES6 you can use the import keyword like this:
async function getData(){
try{
const response = await import('../services/contributors.JSON')
return response.json()
}catch(err){
return err
}
Upvotes: 6
Reputation: 972
After series of hours trying to understand some comments here, I found out that the public folder is in the Root folder of the React app and not somewhere else because I was busy searching for a public folder that was not missing.
So for anyone and newbies like us still wondering where the public folder is, Its located rightly in your project folder under the "Node_Modules" folder
Afterwards, I used the following code:
useEffect(() => {
fetch('data.json')
.then(response => response.json())
.then((json) => setData(json))
}, [])
and viola, my json files were fetched !
Upvotes: 7
Reputation: 459
Use fetch
fetch("../services/contributors.JSON")
.then(res => res.json())
.then(data => console.log(data))
I hope this helps
Upvotes: 45
Reputation: 186
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
}
});
Upvotes: 4
Reputation: 34396
You'll need to run your web page from a web server, due to browser security restrictions. You can do that very easily by making sure you first have Node.js installed, then installing a simple development server:
npm install -g http-server
Then from your console/terminal, navigate to the directory with your code in it, and run:
http-server
Finally, update your JavaScript code to load it like you'd do with any other server call:
async function loadJSON (url) {
const res = await fetch(url);
return await res.json();
}
loadJSON('../services/contributors.JSON').then(data => {
console.log(data[0].name);
});
and then load the page from http://localhost:8080
(or whatever port you ran your http server on).
Upvotes: 6