如何解析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:

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

var data = [
    {
      "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"
    }
];

for (var i = 0; i < data.length; i++)
{
    var obj = data[i];
    console.log(`Name: ${obj.last_name}, ${obj.first_name}`);
}

https://jsfiddle.net/c9wupvo6/

Json相关问答推荐

PowerShell:将Invoke-WebRequest与变量一起使用

使用不同行数的数据创建嵌套Jolt

如何按键过滤

使用 JQ 获取 JSON 中的替代元素(输出:JSON 对象)

如何使用 jq 将字符串数组转换为对象?

如何加入或合并列表元素列表(未知长度)

如何从 json 中获取单个元素?

jq搜索特定字符串并输出对应的父值

Json.NET SerializeObject 转义值以防止 XSS

Swift:如何从字典中删除空值?

未捕获的类型错误:无法读取 null 的属性props

json.dumps 打乱了顺序

在 JSON 反序列化期间没有为System.String类型定义无参数构造函数

jQuery.getJSON 和 jQuery.parseJSON 返回 [object Object]?

使用杰克逊创建一个 json 对象

如何向(JSON)对象的原型添加方法?

Django:TypeError:[] 不是 JSON 可序列化的为什么?

设置对象不是 JSON 可序列化的

从调试器获取 IntelliJ Idea 中的 JSON 对象

在 iPhone 上解析 JSON 日期