How to Read a JSON file in JavaScript

The term JSON is an abbreviation used for Javascript Object Notation. JSON is a text-based data interchange format that is designed for the transmitting of structured data. JSON nowadays is becoming more and more popular. Experts believe that it is a very tough competitor of XML. Although both have the same purpose, the JSON has a high advantage to be used over XML. Both of them are mainly used for plain text data exchange.

JSON has a straightforward and elegant way of representing the data. They can often be viewed as key-value pairs. Also, they acquire a much lesser line of code than the XML, which needs different tags.

Comparison of JSON and XML  with the help of an object named “employees”:

JSON Data

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

XML Data

<employees>
  <element>
    <firstName>Riya</firstName>
    <lastName>Sharma</lastName>
  </element>
  <element>
    <firstName>Salman</firstName>
    <lastName>Singh</lastName>
  </element>
  <element>
    <firstName>Rahul</firstName>
    <lastName>Khan</lastName>
  </element>
</employees>

It is very clearly visible from the above code that the object is more efficiently represented in JSON than in XML. The code written is shorter and hence takes much less time and space. As a result, JSON is increasingly popular as plain text data exchange over the internet.

How to Read a JSON file in Javascript

To read a JSON file in JavaScript:

  1. Using require() function.
  2. Using fetch() function.
  3. Read JSON File from URL using the loadJSON() function.

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"
    }
  ]
}

Read a JSON file using require() function in JavaScript

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 in the server.

Create an app.js file where the employee.json file is and add the following code.

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

Output

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

Read JSON file in Javascript using fetch() function

The fetch() is a built-in JavaScript function that fetches a file from the given path that we specify inside it 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.

After reading the file using the fetch() function, we need to parse the file in actual JSON format using the JSON() function.

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' }
  ]
}

Read JSON file from URL using 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 that the function is executed before the other functions.

There are tons of websites available on the internet that contain JSON data for testing purposes to test your algorithm. The JSON files can also be read from URLs. However, several methods are available to read JSON data from a URL in Javascript like jquery, loadJSON, etc. But we will use the loadJSON() function to read a JSON file from the URL.

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]);
}

Here, we are defining the getData() function. As soon as the data is read from the JSON website, it is passed directly to the function getData(), and the function getData() has a data parameter.

In our example, we define the first element’s data from the JSON website URL.

That’s it for this tutorial.

See also

How to Read an Array of Objects in JavaScript

 

Leave a Comment