How to Read a JSON file in JavaScript

To read a JSON file in JavaScript, you can use the “require()”, “fetch()”, or “loadJSON()” function.

Method 1: Using a require() function

To load files and modules in Javascript, 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.

Example

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

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

Example

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 loadJSON() function

The loadJSON() is a built-in JavaScript function used to read the contents of a JSON file or URL and return it as an object. The loadJSON() function is asynchronous; therefore, it is recommended to be called in the preload() function to ensure it is executed before the other functions.

Syntax

loadJSON(link, function, optional)

Arguments

The loadJSON() function accepts three parameters:

  • Link: In this, we specify the URL of the Page where JSON data is present.
  • Function: This is the function to which the data read by URL will be transferred.
  • Optional: This is an optional parameter in the loadJSON() function that is used to define data security sometimes.

Example

loadJSON("https://jsonplaceholder.typicode.com/posts", getData, 'jsonp');

function getData(Data) {
  console.log(Data[0]);
}

That’s it.

Leave a Comment