165

I'm new to React and I'm trying to import a JSON DATA variable from an external file. I'm getting the following error:

Cannot find module "./customData.json"

Could some one help me? It works if I have my DATA variable in index.js but not when it's in an external JSON file.

index.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import customData from './customData.json';
import Profile from './components/profile';
import Hobbies from './components/hobbies';

class App extends Component {
  render() {
    return (
      <div>
        <Profile name={this.props.profileData.name}imgUrl={this.props.profileData.imgURL} />
        <Hobbies hobbyList={this.props.profileData.hobbyList}/>
      </div>
    );
  }
}

ReactDOM.render(<App profileData={DATA}/>, document.querySelector('.container'));
hobbies.js
import React, {Component} from 'react';

var Hobbies = React.createClass({
  render: function(){
    var hobbies = this.props.hobbyList.map(function(hobby, index){
        return (<li key={index}>{hobby}</li>);
    });
    return (
        <div>
            <h5>My hobbies:</h5>
            <ul>
                {hobbies}
            </ul>
        </div>
    );
  } 
});

export default Hobbies;
profile.js
import React from 'react';

var Profile = React.createClass({
render: function(){
    return (
        <div>
            <h3>{this.props.name}</h3>
            <img src={this.props.imgUrl} />
        </div>
    )
  }
});

export default Profile
customData.json
var DATA = {    
    name: 'John Smith',
    imgURL: 'http://lorempixel.com/100/100/',
    hobbyList: ['coding', 'writing', 'skiing']
}

export default DATA
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
Hugo Seleiro
  • 2,467
  • 5
  • 26
  • 39

15 Answers15

158

A nice way to do this would be using the json-loader module. This way you don't need to add a fake .js extension (which is intended for code rather than data/config). This module is already included in create-react-app and Webpack 2.x+ (current version is 5.x), so if you use any of these tools, you can easily import your json without any additional configs/dependencies:

import Profile from './components/profile';

See this answer for more details.

Javad
  • 5,755
  • 4
  • 41
  • 51
  • 9
    Strange. When I try to import a json file in `create-react-app`, it returns `undefined` – developarvin Mar 08 '18 at 02:48
  • 3
    IMHO, [this other answer](https://stackoverflow.com/a/52349546/76583) should be really the accepted answer. This one is indeed a solution but only for a subset of React apps - only the ones started with create-react-app. – Seb Oct 30 '20 at 20:16
  • 1
    fyi, this works. except I had an edge case where the json file cannot have an underscore in it's name. i.e. `/profile.json` is ok, but `/my_profile.json` is not. – BigRon Dec 04 '21 at 14:30
  • @Seb See my last edit. This solution also applies to all projects that use Webpack - which is most of the react apps today and majority of all web apps really. Also, you can add the `json-loader` module to any web app even if it don't use webpack, so it has no limitations. – Javad Jun 30 '23 at 01:09
97

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.

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:

admins.json
[{
  "userName": "tech1337",
  "passSalted": "xxxxxxxxxxxx"
}]

Note the quoted keys, "userName", "passSalted"!

I can do the following and get the data out of the file with ease.

let admins = require('~/app/admins.json');
console.log(admins[0].userName);

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

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
Tech1337
  • 1,557
  • 13
  • 16
  • 14
    Definitely the correct answer. Shouldn't need a third-party module to read in JSON data. – ngoue Oct 08 '18 at 15:42
  • 4
    The double quotes around the keys are required for properly formatted JSON. Also, JSON can not have comments. – Let Me Tink About It May 23 '20 at 16:33
  • 1
    This is the way to go – Lautaro Jorge Garcia Feb 27 '22 at 01:44
  • 2
    This doesn't answer the question of how to load a JSON file in a React app. There is no "Node" in a React app. What you might want to suggest is having the JSON payload served by the back-end and making a call to it, but telling them to use `require` doesn't help the OP at all. – Michael Oryl May 17 '22 at 17:40
  • 1
    I wrote this answer a while back, and it does indeed make some assumptions and glosses over the options available for implementing `require` in your React or other JS framework application. It may be poorly worded, but I was eluding to the Node `require` syntax more than Node.js itself. The default CRA config will transpile `require` for the web, but you could also use `browserify` instead to the same effect. – Tech1337 May 28 '22 at 01:32
  • @LICON99 this may be what's happening in your code. Just you did not show it. – tevemadar Jul 13 '23 at 23:51
19

With json-loader installed, you can use

import customData from '../customData.json';

or also, even more simply

import customData from '../customData';

To install json-loader

npm install --save-dev json-loader
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
17

Simplest approach is following

// Save this as someJson.js
const someJson = {
  name: 'Name',
  age: 20
}

export default someJson

then

import someJson from './someJson'
dev_khan
  • 709
  • 7
  • 16
17

React 17 created from create-react-app, importing json just work by default.

import config from './config.json'
s1n7ax
  • 2,750
  • 6
  • 24
  • 53
11

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

fetch('./data.json').then(response => {
      console.log(response);
      return response.json();
    }).then(data => {
      // Work with JSON data here
      console.log(data);
    }).catch(err => {
      // Do something for an error here
      console.log("Error Reading data " + err);
    });

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. So we have to explicitly move data.json file from src to public directory.

Akash Kumar Seth
  • 1,651
  • 1
  • 18
  • 22
10

Please store your JSON file with the .js extension and make sure that your JSON should be in same directory.

adkl
  • 634
  • 7
  • 17
Shubham
  • 1,163
  • 2
  • 12
  • 36
10

In current react build you simply import and use:

import jsonData from 'path/to/myJson.json'
Avi E. Koenig
  • 360
  • 5
  • 13
8

// rename the .json file to .js and keep in src folder

Declare the json object as a variable

var customData = {
   "key":"value"
};

Export it using module.exports

module.exports = customData;

From the component that needs it, make sure to back out two folders deep

import customData from '../customData';

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
cesar3sparza
  • 129
  • 1
  • 3
7

try with export default DATA or module.exports = DATA

Salvatore
  • 177
  • 9
  • uhm have you tried with require instead of import ? but i'm pretty sure that this is not the problem, the path is correct? oh and try also to write import DATA instead of customData. – Salvatore Sep 25 '16 at 11:35
7

there are multiple ways to do this without using any third-party code or libraries (the recommended way).

1st STATIC WAY: create a .json file then import it in your react component example

my file name is "example.json"

{"example" : "my text"}

the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.

How to import in react component

import myJson from "jsonlocation";

and you can use it anywhere like this

myJson.example

now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.

Now, what about if we want to dynamically import the JSON data? example a multi-language support website?

2 DYNAMIC WAY

1st declare your JSON file exactly like my example above

but this time we are importing the data differently.

let language = require('./en.json');

this can access the same way.

but wait where is the dynamic load?

here is how to load the JSON dynamically

let language = require(`./${variable}.json`);

now make sure all your JSON files are within the same directory

here you can use the JSON the same way as the first example

myJson.example

what changed? the way we import because it is the only thing we really need.

I hope this helps.

jerryurenaa
  • 3,863
  • 1
  • 27
  • 17
3
var langs={
  ar_AR:require('./locale/ar_AR.json'),
  cs_CZ:require('./locale/cs_CZ.json'),
  de_DE:require('./locale/de_DE.json'),
  el_GR:require('./locale/el_GR.json'),
  en_GB:require('./locale/en_GB.json'),
  es_ES:require('./locale/es_ES.json'),
  fr_FR:require('./locale/fr_FR.json'),
  hu_HU:require('./locale/hu_HU.json')
}
module.exports=langs;

Require it in your module:

let langs=require('./languages');

regards

rabie jegham
  • 125
  • 2
  • 3
1

My friends, if you are using React and TypeScript, just do these steps and DONE!

  1. In the tsconfig.json add these 2 new lines:

     // tsconfig.json
     {
        "compilerOptions": {
           // ... other options
           "esModuleInterop": true,
           "resolveJsonModule": true
         }
     }
    
  2. Import your json:

    import yourJSON from "./data/yourJSON.json"
    
-1

This worked well in React 16.11.0

// in customData.js
export const customData = {
  //json data here
  name: 'John Smith',
  imgURL: 'http://lorempixel.com/100/100/',
  hobbyList: ['coding', 'writing', 'skiing']
}
// in index.js
import { customData } from './customData';

// example usage later in index.js
<p>{customData.name}</p>
Buldo
  • 99
  • 7
  • 7
    This is not a JSON – Rambalac Mar 24 '21 at 01:21
  • @Rambalac the customData.js file contains json. We import that file into index.js – Buldo Mar 26 '21 at 08:19
  • The problem that JSON has it's own strict specification and this simple JS file doesn't fulfill these criteria. So your solution is just a handling of the standard JS file that contains JSON. It's like a workaround but it doesn't provide an answer regarding Topic. It's like: `Please, give to me a suggestion what is the faster bus to Maiami? Well, just buy an airline ticket`. Both do the same but there is a nuance – Velidan May 25 '23 at 05:53
-2

Something that worked for me was to simply place the JSON file in the public folder. You can simply import in any js using

brain.loadData("exampleFile.json");

It is as simple as that I guess. Definitely worth a try :D

Salma Elshahawy
  • 1,112
  • 2
  • 11
  • 21
  • 2
    what is `brain` ? this looks like a method on something that is doing a http fetch ? – dcsan Mar 23 '21 at 22:29
  • I just used `brain` as an example. It is actually an ml5.js instance. But during import, I was not able to access the json even after importing. Putting the json file in public folder helped me access it. – Ujjwal Sharma Sep 11 '21 at 13:27