Import Json File In React

Posted on  by admin

Import JSON File in React

Modified1 month ago. I'm new to React and I'm trying to import a JSON DATA variable from an external file.

Use Case

  1. I'm getting the following error: .
  2. Cannot find module "./customData.json".
  3. Could some one help me?
  4. It works if I have my DATA variable in index.js but not when it's in an external JSON file.

Load JSON Data into Stocks Component

index.jshobbies.jsprofile.jscustomData.json . 184184 bronze badges.

2,08155 gold badges2323 silver badges3434 bronze badges.

2323 silver badges3434 bronze badges. One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module.

If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:.

This answer explains more. 44 gold badges3939 silver badges5050 bronze badges.

Display Stock Information In a Tabular Format

5050 bronze badges. This old chestnut.. In short, you should be using require and letting node handle the parsing as part of the require call, not outsourcing it to a 3rd party module.

You should also be taking care that your configs are bulletproof, which means you should check the returned data carefully.

Create Stocks Component

But for brevity's sake, consider the following example:. For Example, let's say I have a config file 'admins.json' in the root of my app containing the following:.

Note the quoted keys, "userName", "passSalted"! I can do the following and get the data out of the file with ease.

Access Code on Github

Now the data is in and can be used as a regular (or array of) object.

184184 bronze badges. With json-loader installed, you can use.

or also, even more simply. To install json-loader.

Not the answer you're looking for? Browse other questions tagged javascriptjsonreactjs or ask your own question.

1616 gold badges8686 silver badges184184 bronze badges. 184184 bronze badges. The solution that worked for me is that:-I moved my data.json file from src to public directory.Then used fetch API to fetch the file.

The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory.

Set Up React App