我们的目录中有一个employee.json文件,在同一个目录中,我们有一个js文件,我们要在其中导入json文件的内容。
employee.json的内容-
employee.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模块访问employee.json的代码-
const data = require('./employees.json'); console.log(data);
使用fetch函数访问employee.json的代码-
fetch("./employees.json") .then(response => { return response.json(); }) .then(data => console.log(data));
注–虽然第一个功能更适合于节点环境,但是第二个功能仅在Web环境中有效,因为仅在Web环境中才能访问fetch API。
使用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' } ] }