184

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
1
  • 10
    Your customData.json is not a JSON. Commented Mar 24, 2021 at 1:24

15 Answers 15

172

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.

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

5 Comments

Strange. When I try to import a json file in create-react-app, it returns undefined
IMHO, this other answer 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.
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.
@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.
NB: if you are using a dynamic import (e.g. const module = await import('./components/profile') make sure you access the json through the default attribute (i.e. const profile = module.default) rather than just module otherwise you will find the default key in addition to your json keys. See the answer on How to dynamically load a JSON file in React? for other examples.
105

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.

5 Comments

Definitely the correct answer. Shouldn't need a third-party module to read in JSON data.
The double quotes around the keys are required for properly formatted JSON. Also, JSON can not have comments.
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.
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.
@LICON99 this may be what's happening in your code. Just you did not show it.
22

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

import config from './config.json'

Comments

20

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

Comments

17

Simplest approach is following

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

export default someJson

then

import someJson from './someJson'

2 Comments

This is not a JSON.
This is a JavaScript object not a JSON object
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.

Comments

10

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

1 Comment

Solved !! Thanks for the answer !!
10

In current react build you simply import and use:

import jsonData from 'path/to/myJson.json'

Comments

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';

Comments

7

try with export default DATA or module.exports = DATA

1 Comment

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

Comments

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

Comments

3

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"
    

Comments

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

3 Comments

This is not a JSON
@Rambalac the customData.js file contains json. We import that file into index.js
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
-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

2 Comments

what is brain ? this looks like a method on something that is doing a http fetch ?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.