如何解析React js中的本地JSON文件? [英] How can I parse through local JSON file in React js?

查看:1843
本文介绍了如何解析React js中的本地JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过JSON文件解析检索其所有数据并在我的代码中使用它?

How can I parse through a JSON file retrieving all its data and using it in my code?

我尝试导入文件并尝试使用控制台记录它,但它只是打印对象{}:

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);

这就是我的file.json的样子:

This is what my file.json looks like:

[
    {
      "id": 1,
      "gender": "Female",
      "first_name": "Helen",
      "last_name": "Nguyen",
      "email": "hnguyen0@bloomberg.com",
      "ip_address": "227.211.25.18"
    }, {
      "id": 2,
      "gender": "Male",
      "first_name": "Carlos",
      "last_name": "Fowler",
      "email": "cfowler1@gnu.org",
      "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.

推荐答案

var data = require('../../file.json'); // forward slashes will depend on the file location

for(var i = 0; i < data.length; i++) {
    var obj = data[i];

    console.log("Name: " + obj.first_name + ", " + obj.last_name);
}

https://jsfiddle.net/c9wupvo6/

这篇关于如何解析React js中的本地JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆