How to Read a JSON file in JavaScript

Here are three ways to read a JSON file in JavaScript:

  1. Using require()
  2. Using fetch()
  3. Using the ES6 Import

Method 1: Using a require() function

Visualization of Using a require() function

To load files and modules, use the require() function. The require() function takes the path of the file, and with the help of the console.log() function, it displays the data on the server.

const jsonFile = require("./employee.json");
console.log(jsonFile);

Output

{
   employees: [
    { firstName: 'Riya', lastName: 'Sharma' },
    { firstName: 'Salman', lastName: 'Singh' },
    { firstName: 'Rahul', lastName: 'Khan' }
  ]
}

Here, we are taking an example employee.json file given below. Put this file inside your current project directory.

{
   "employees": [
    {
       "firstName": "Riya",
       "lastName": "Sharma"
    },
    { 
       "firstName": "Salman",
       "lastName": "Singh"
    },
    {
       "firstName": "Rahul",
       "lastName": "Khan"
    }
  ]
}

Method 2: Using the fetch() function

Visualization of using the fetch() function

The fetch() function fetches a file from the path we specify and returns the file using the console.log() function. It works only in web-based environments as API works only in web-based environments.

import fetch from 'node-fetch';

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

Output

{
   employees: [
    { firstName: 'Riya', lastName: 'Sharma' },
    { firstName: 'Salman', lastName: 'Singh' },
    { firstName: 'Rahul', lastName: 'Khan' }
  ]
}

Method 3: Using the ES6 Import

Visualization of using the ES6 Import

In ES6, you can use the “import statement” to import JSON files just as you would with JavaScript modules. However, whether this will work out-of-the-box depends on your build system or runtime environment.

For example, in Webpack (since version 2), you can import JSON files directly, and it will be treated as a JavaScript module:

Let’s assume you have a file named data.json in the same directory.

// app.js

import data from './employee.json';

console.log(data);

The console.log() method will log the data.

Output

{
   employees: [
    { firstName: 'Riya', lastName: 'Sharma' },
    { firstName: 'Salman', lastName: 'Singh' },
    { firstName: 'Rahul', lastName: 'Khan' }
  ]
}

That’s it!

Related posts

How to Read a JSON file in JavaScript

Read a JSON File in TypeScript

Read a Local Text File in JavaScript