Fetching local JSON

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).


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 !


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

Use fetch

fetch("../services/contributors.JSON")
.then(res => res.json())
.then(data => console.log(data))

I hope this helps