[javascript] 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

This question is related to javascript json reactjs

The answer is


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


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.


try with export default DATA or module.exports = DATA


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.


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


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

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


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>

Simplest approach is following

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

export default someJson

then

import someJson from './someJson'

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.


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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release