如何将本地JSON文件数据导入到我的JavaScript变量
我们在一个目录中有一个 员工.json 文件,在同一目录下我们有一个js文件,我们想要导入json文件的内容。
employees.json的内容 –
员工.json
"Employees" : [
{
"userId":"ravjy", "jobTitleName":"Developer", "firstName":"Ran","lastName":"Vijay",
"preferredFullName":"Ran Vijay","employeeCode":"H9","region":"DL","phoneNumber":"34567689",
"emailAddress":"ranvijay.k.ran@gmail.com"
},
{
"userId":"mrvjy","jobTitleName":"Developer","firstName":"Murli","lastName":"Vijay",
"preferredFullName":"Murli Vijay","employeeCode":"A2","region":"MU",
"phoneNumber":"6543565","emailAddress":"murli@vijay.com"
}
]
}
我们可以使用以下两种方式之一来访问json文件:
使用require模块
访问”employees.json”的代码使用 require 模块 –
const data = require('./employees.json');
console.log(data);
使用fetch函数
使用fetch函数访问”employees.json”的代码fetch函数-
fetch("./employees.json")
.then(response => {
return response.json();
})
.then(data => console.log(data));
注意 − 第一个函数更适用于Node环境,而第二个函数只能在Web环境中使用,因为fetch API仅在Web环境中可访问。
运行上述任何一个使用require或fetch函数后,控制台输出如下 −
{
Employees: [
{
userId: 'ravjy',
jobTitleName: 'Developer',
firstName: 'Ran',
lastName: 'Vijay',
preferredFullName: 'Ran Vijay',
employeeCode: 'H9',
region: 'DL',
phoneNumber: '34567689',
emailAddress: 'ranvijay.k.ran@gmail.com'
},
{
userId: 'mrvjy',
jobTitleName: 'Developer',
firstName: 'Murli',
lastName: 'Vijay',
preferredFullName: 'Murli Vijay',
employeeCode: 'A2',
region: 'MU',
phoneNumber: '6543565',
emailAddress: 'murli@vijay.com'
}
]
}