21

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!

PepperAddict
  • 888
  • 2
  • 10
  • 16
  • 1
    move the `require` to the top of your file, outside of the component – Anthony Mar 25 '18 at 23:11
  • 1
    Possible duplicate of [How can I parse through local JSON file in React js?](https://stackoverflow.com/questions/37649695/how-can-i-parse-through-local-json-file-in-react-js) – pegla Mar 25 '18 at 23:13
  • 1
    What error are you getting? Are you using webpack/browserify or similar? – acdcjunior Mar 25 '18 at 23:52
  • thank you for getting back to me @acdcjunior I just keep getting undefined. Still trying to get this to work. *sigh* Trying it different ways right now. – PepperAddict Mar 26 '18 at 00:03
  • 1
    Are you using webpack/browserify or similar? – acdcjunior Mar 26 '18 at 00:03
  • hmm sorry @ackdcjunior I was getting a bit nervous about answering this since I'm not entirely sure. This is for a group project so I'm not sure what's in there. For sure I know we're not using webpack. Do you think if we were using something like that I would run into that problem? – PepperAddict Mar 26 '18 at 00:15

5 Answers5

44

Use fetch

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

I hope this helps

Ayeksius
  • 449
  • 6
  • 10
  • how can fetch api load a file in url ?, i am getting error `file in URL is not accepted` – Rohan Devaki Oct 06 '21 at 07:13
  • @RohanDevaki Are you trying to download a file or to upload a file? If your downloading from an api you need to use arrayBuffer as a response type in your request. – Ayeksius Oct 07 '21 at 14:55
7

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 !

Olasunkanmi
  • 902
  • 15
  • 23
  • 1
    This is not a direct answer to the original question, but might be useful for people like me who came here like me looking to just read a static json file into react. It turns out that in parcel and at least the webpack setup create-react-app generates, you can skip the fetch api and just bring the data in with an import statement. Here it is in parcel docs for example: https://parceljs.org/languages/json/ There might be some specific use cases for using fetch api for json data bundled in your app, but if you're just trying to read it this works. – alex.h Feb 19 '22 at 22:26
6

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

Nathan Ridley
  • 33,766
  • 35
  • 123
  • 197
  • Thank you so much Nathan! I've been troubleshooting this error for hours now and your answer finally helped me. – Muriel Jul 27 '20 at 10:05
5

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
  }
gildniy
  • 3,528
  • 1
  • 33
  • 23
  • I believe the dynamic import will automatically convert the json file contents into a JS object. So no need to call `.json()` on the response. – Adam Harte Apr 19 '23 at 22:08
4

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
  }
});
Ben E
  • 176
  • 1
  • 4