Javascript 如何在 React js 中解析本地 JSON 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37649695/
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
How can I parse through local JSON file in React js?
提问by Parkicism
How can I parse through a JSON file retrieving all its data and using it in my code?
如何解析 JSON 文件以检索其所有数据并在我的代码中使用它?
I've tried importing the file and just tried console logging it, but all it does is print Object {}:
我试过导入文件并尝试控制台记录它,但它所做的只是打印对象{}:
import jsonData from "./file.json";
console.log(jsonData);
This is what my file.json looks like:
这是我的 file.json 的样子:
[
{
"id": 1,
"gender": "Female",
"first_name": "Helen",
"last_name": "Nguyen",
"email": "[email protected]",
"ip_address": "227.211.25.18"
}, {
"id": 2,
"gender": "Male",
"first_name": "Carlos",
"last_name": "Fowler",
"email": "[email protected]",
"ip_address": "214.248.201.11"
}
]
I'd want to be able to access the first and last name of each component and print those on the website.
我希望能够访问每个组件的名字和姓氏,并将它们打印在网站上。
回答by fulvio
var data = require('../../file.json'); // forward slashes will depend on the file location
var data = [
{
"id": 1,
"gender": "Female",
"first_name": "Helen",
"last_name": "Nguyen",
"email": "[email protected]",
"ip_address": "227.211.25.18"
}, {
"id": 2,
"gender": "Male",
"first_name": "Carlos",
"last_name": "Fowler",
"email": "[email protected]",
"ip_address": "214.248.201.11"
}
];
for (var i = 0; i < data.length; i++)
{
var obj = data[i];
console.log("Name: " + obj.first_name + ", " + obj.last_name);
}
回答by patad
I also had problems with getting an empty Object back. Even when using require
as suggested above.
我也遇到了取回空对象的问题。即使require
按照上面的建议使用。
fetch
however solved my problem:
fetch
但是解决了我的问题:
fetch('./data/fakeData.json')
.then((res) => res.json())
.then((data) => {
console.log('data:', data);
})
(As of today, the support isn't optimal though: http://caniuse.com/#feat=fetch)
(截至今天,支持不是最佳的:http: //caniuse.com/#feat=fetch)
回答by erich2k8
Applications packaged with webpack 2.0.0+ (such as those created with create-react-app) support imports from json exactly as in the question (see this answer.
使用 webpack 2.0.0+ 打包的应用程序(例如使用create-react-app 创建的应用程序)完全按照问题支持从 json 导入(请参阅此答案.
Be aware that import
caches the result, even if that result is parsed json, so if you modify that object, other modules that also import it have references to the same object, not a newly parsed copy.
请注意import
缓存结果,即使该结果是解析 json,因此如果您修改该对象,其他导入它的模块也会引用同一个对象,而不是新解析的副本。
To get a "clean" copy, you can make a function that clones it such as:
要获得“干净”的副本,您可以创建一个克隆它的函数,例如:
import jsonData from './file.json';
const loadData = () => JSON.parse(JSON.stringify(jsonData));
Or if you're using lodash:
或者,如果您正在使用lodash:
import jsonData from './file.json';
import { cloneDeep } from 'lodash';
const loadData = () => cloneDeep(jsonData);
回答by Parkicism
For those of you who also have trouble with this, this code seemed to have fixed the problem
对于那些也有这个问题的人,这段代码似乎已经解决了这个问题
var jsonData = require('../../file.json');
class blah extends React.Component {
render(){
var data;
function loadJSON(jsonfile, callback) {
var jsonObj = new XMLHttpRequest();
jsonObj.overrideMimeType("application/json");
jsonObj.open('GET', "../../file.json", true);
jsonObj.onreadystatechange = function () {
if (jsonObj.readyState == 4 && jsonObj.status == "200") {
callback(jsonObj.responseText);
}
};
jsonObj.send(null);
}
function load() {
loadJSON(jsonData, function(response) {
data = JSON.parse(response);
console.log(data);
});
}
load();
}
}
回答by fireflycaptainz
The JS spread operator also helps to get a deep copy of the object.
JS 扩展运算符还有助于获取对象的深层副本。
import jsonData from '../../file.json';
const loadData = [...jsonData];