Javascript 在 React 中导入 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39686035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Import JSON file in React
提问by Hugo Seleiro
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:
我是 React 的新手,我正在尝试DATA
从外部文件导入 JSON变量。我收到以下错误:
Cannot find module "./customData.json"
找不到模块“./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.
有人可以帮助我吗?如果我有我的DATA
变量,index.js
但当它在外部 JSON 文件中时,它会起作用。
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'));
爱好.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;
配置文件.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
自定义数据.json
var DATA = {
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}
export default DATA
回答by Javad Sadeqzadeh
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:
一种不错的方法(不添加用于代码而不是用于数据和配置的假 .js 扩展名)是使用 module.js json-loader
。如果你曾经create-react-app
搭建过你的项目,模块已经包含在内,你只需要导入你的json:
import Profile from './components/profile';
Thisanswer explains more.
这个答案解释了更多。
回答by Tech1337
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.
简而言之,您应该使用 require 并让节点将解析作为 require 调用的一部分进行处理,而不是将其外包给第 3 方模块。您还应该注意您的配置是防弹的,这意味着您应该仔细检查返回的数据。
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”,其中包含以下内容:
admins.json[{
"userName": "tech1337",
"passSalted": "xxxxxxxxxxxx"
}]
Note the quoted keys, "userName"
, "passSalted"
!
请注意引用的键"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.
现在数据已经存在并且可以用作常规(或数组)对象。
回答by Let Me Tink About It
With json-loader
installed, you can use
随着json-loader
安装,您可以使用
import customData from '../customData.json';
or also, even more simply
或者,甚至更简单
import customData from '../customData';
To install json-loader
安装 json-loader
npm install --save-dev json-loader
回答by Akash Kumar Seth
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
对我有用的解决方案是:- 我将 data.json 文件从 src 移动到公共目录。然后使用 fetch API 来获取文件
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.
问题是,在编译 react 应用程序后,获取请求会在 URL“ http://localhost:3000/data.json”中查找文件,这实际上是我的 react 应用程序的公共目录。但不幸的是,在编译 react app 时 data.json 文件没有从 src 移动到 public 目录。所以我们必须明确地将 data.json 文件从 src 移动到 public 目录。
回答by Shubham
Please store your JSON file with the .js extension and make sure that your JSON should be in same directory.
请使用 .js 扩展名存储您的 JSON 文件,并确保您的 JSON 应位于同一目录中。
回答by Salvatore
try with export default DATA
or module.exports = DATA
尝试export default DATA
或 module.exports = DATA
回答by dev_khan
Simplest approach is following
最简单的方法如下
// Save this as someJson.js
const someJson = {
name: 'Name',
age: 20
}
export default someJson
then
然后
import someJson from './someJson'
回答by cesar3sparza
// rename the .json file to .js and keep in src folder
// 将 .json 文件重命名为 .js 并保存在 src 文件夹中
Declare the json object as a variable
将json对象声明为变量
var customData = {
"key":"value"
};
Export it using module.exports
使用 module.exports 导出
module.exports = customData;
module.exports = customData;
From the component that needs it, make sure to back out two folders deep
从需要它的组件中,确保回退两个文件夹深
import customData from '../customData';
import customData from '../customData';
回答by Buldo
This worked well in React 16.11.0
这在 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>