Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

javascript - How can I parse through local JSON file in React js?

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

This is what my file.json looks like:

[
    {
      "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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.last_name}, ${obj.first_name}`);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...