Hugo Seleiro
Hugo Seleiro

Reputation: 2657

Import JSON file in React

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

Upvotes: 182

Views: 410704

Answers (15)

Javad
Javad

Reputation: 6016

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.

Upvotes: 170

Mohammad Farhadi
Mohammad Farhadi

Reputation: 1482

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"
    

Upvotes: 3

Avi E. Koenig
Avi E. Koenig

Reputation: 379

In current react build you simply import and use:

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

Upvotes: 10

s1n7ax
s1n7ax

Reputation: 3069

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

import config from './config.json'

Upvotes: 21

Buldo
Buldo

Reputation: 99

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>

Upvotes: -1

Ujjwal Sharma
Ujjwal Sharma

Reputation: 1

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

Upvotes: -2

rabie jegham
rabie jegham

Reputation: 125

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

Upvotes: 3

jerryurenaa
jerryurenaa

Reputation: 4704

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.

Upvotes: 7

Tech1337
Tech1337

Reputation: 1677

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.

Upvotes: 104

dev_khan
dev_khan

Reputation: 717

Simplest approach is following

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

export default someJson

then

import someJson from './someJson'

Upvotes: 17

cesar3sparza
cesar3sparza

Reputation: 129

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

Upvotes: 8

Akash Kumar Seth
Akash Kumar Seth

Reputation: 1701

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.

Upvotes: 11

Let Me Tink About It
Let Me Tink About It

Reputation: 16102

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

Upvotes: 20

Shubham
Shubham

Reputation: 1191

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

Upvotes: 10

Salvatore
Salvatore

Reputation: 177

try with export default DATA or module.exports = DATA

Upvotes: 7

Related Questions