Reactjs Read Json File

Posted on  by admin

Modified4 years, 10 months ago. I have to read JSON file using React.js which is stored in local drive in Mac.

I tried using fetch() api but I get data undefined.Heres my code. I am getting data as undefined.How will I be able to read JSON file in react.js?


22 gold badges77 silver badges1515 bronze badges. 1515 bronze badges.

The json() method of the Body mixin takes a Response stream and reads it to completion.

It returns a promise that resolves with the result of parsing the body text as JSON. 33 gold badges2525 silver badges3636 bronze badges5.

3636 bronze badges.

Use Case

When building applications in React, we often need to work with JSON data.This data could come from third party APIs or be read from external files.In this guide, we will work on a code example to load the JSON data from a file and renderit inside a React component.

Say you have a data set in JSON format containing information onfinancial stocks from multiple companies.

Each stock has metadata associatedwith it.

  • Your goal is to read that data from an external file and render it onthe web page in a tabular format, as shown below.
  • Open your terminal and run these commands to use Create React App to get a sample app running on your machine.
  • Now, to run the app in the development mode, open http://localhost:3000 in your browser.

You should see the sample app running with a React logo.

Why did you not use Axios or Fetch?

Create a file in your project at location src/data.js and add the data below in your data.js file.

stockData is a JSON array containing dummy stock prices of some companies.

Each JSON object inside this array contains four things:.

  • Using export const allows you to define and initialize variables that can be imported into any React component.
  • In fact, you'll shortly import stockData as a JavaScript object in the next step. It's time to update our component because we need to render JSON data into our components.
  • So head to the src/App.js file and remove all the boilerplate code that came with it.