Computer >> Computer tutorials >  >> Programming >> Javascript

How to import local json file data to my JavaScript variable?


We have an employee.json file in a directory, within the same directory we have a js file, in which we want to import the content of the json file.

The content of employees.json −

employees.json

"Employees" : [
   {
      "userId":"ravjy", "jobTitleName":"Developer", "firstName":"Ran","lastName":"Vijay",
      "preferredFullName":"Ran Vijay","employeeCode":"H9","region":"DL","phoneNumber":"34567689",
      "emailAddress":"[email protected]"
   },
   {
      "userId":"mrvjy","jobTitleName":"Developer","firstName":"Murli","lastName":"Vijay",
      "preferredFullName":"Murli Vijay","employeeCode":"A2","region":"MU",
      "phoneNumber":"6543565","emailAddress":"[email protected]"
      }
   ]
}

We can use any of the two ways to access the json file −

Using require module

Code to access employees.json using require module −

const data = require('./employees.json');
console.log(data);

Using fetch function

Code to access employees.json using fetch function −

fetch("./employees.json")
.then(response => {
   return response.json();
})
.then(data => console.log(data));

Note − While the first function is better suited for node environment, the second function only works in the web environment because the fetch API is only accessible in the web environment.

After running any of the above using require or fetch function, the console output is as follows −

{
   Employees: [
      {
         userId: 'ravjy',
         jobTitleName: 'Developer',
         firstName: 'Ran',
         lastName: 'Vijay',
         preferredFullName: 'Ran Vijay',
         employeeCode: 'H9',
         region: 'DL',
         phoneNumber: '34567689',
         emailAddress: '[email protected]'
      },
      {
         userId: 'mrvjy',
         jobTitleName: 'Developer',
         firstName: 'Murli',
         lastName: 'Vijay',
         preferredFullName: 'Murli Vijay',
         employeeCode: 'A2',
         region: 'MU',
         phoneNumber: '6543565',
         emailAddress: '[email protected]'
      }
   ]
}