Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import JSON file in React

People also ask

How can I import a JSON file in React?

To import JSON file in React, we use import to import it like a regular module. import Profile from "./components/profile"; to import the ./components/profile JSON file as Profile . This works because the json-loader Webpack module is included with create-react-app .

How do I import a JSON file into react native?

To fetch data from local JSON file with React Native, we can import the JSON file with import . import * as React from 'react'; import { View, Text } from 'react-native'; import { Card } from 'react-native-paper'; import customData from './customData. json'; const App = () => { return ( <View> <Text>{JSON.


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:

import Profile from './components/profile';

This answer explains more.


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.


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

Simplest approach is following

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

export default someJson

then

import someJson from './someJson'

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