24

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!

6
  • 1
    move the require to the top of your file, outside of the component Commented Mar 25, 2018 at 23:11
  • 1
    Possible duplicate of How can I parse through local JSON file in React js? Commented Mar 25, 2018 at 23:13
  • 1
    What error are you getting? Are you using webpack/browserify or similar? Commented Mar 25, 2018 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. Commented Mar 26, 2018 at 0:03
  • 1
    Are you using webpack/browserify or similar? Commented Mar 26, 2018 at 0:03

5 Answers 5

47

Use fetch

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

I hope this helps

Sign up to request clarification or add additional context in comments.

2 Comments

how can fetch api load a file in url ?, i am getting error file in URL is not accepted
@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.
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 !

1 Comment

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

1 Comment

Thank you so much Nathan! I've been troubleshooting this error for hours now and your answer finally helped me.
6

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 } 

1 Comment

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

3 Comments

Hey, thank you for getting back to me. When I use that I get "TypeError: fs.readFile is not a function"
dont forget to require fs maybe remove node_modules and npm install
@BenE you might want to first establish that they're doing this from the server side and not the client side.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.