Read JSON File using JavaScript

tutorials

JavaScript provides several methods to work with JSON files. JSON is a popular format used for representing structured data in a simple text format. It is often used in APIs, web services, and data exchanges between server and client. In this article, we will explore how to read a JSON file using JavaScript and display its content.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is language-independent but uses conventions that are familiar to programmers of the C-family languages, including JavaScript, Python, and more.

A typical JSON structure looks like this:

javascript
{
 "name": "John Doe",
 "age": 30,
 "isEmployed": true,
 "address": {
   "street": "123 Main St",
   "city": "Anytown"
 }
}

Why to Use JSON in Web Development?

JSON is widely used in web development due to its simplicity and compatibility. Here are a few reasons why JSON is popular:

  • Lightweight: Compared to XML, JSON is more concise and easier to work with.
  • Easy to Read: It is structured in a human-readable format.
  • Native Support in JavaScript: Since JSON is based on JavaScript object syntax, JavaScript can easily parse and stringify JSON data.

Methods to Read a JSON File in JavaScript

There are various ways to read a JSON file using JavaScript. Here are three commonly used methods:

  • Using Fetch API (Modern Method, Works in Browsers)
  • Using XMLHttpRequest (Older Method, Works in Browsers)
  • Using fs Module (in Node.js Environment)

Reading JSON Data using Fetch API

The Fetch API provides an easy, modern way to make HTTP requests and can be used to read JSON data from a file. This method is asynchronous, meaning it won’t block the execution of your code while the data is being fetched.

html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>Read JSON using Fetch API</title>
</head>

<body>
    <h2>Read JSON File</h2>
    
    <pre id="output"></pre>
    
    <script>
    
        // Reading the JSON file using Fetch API
        fetch('data.json')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' 
                        + response.statusText);
                }
                return response.json(); // Parse the JSON data
            })
            .then(data => {

                // Display the JSON data in the HTML element
                document.getElementById('output').textContent 
                    = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                console.error('Error fetching the JSON file:', error);
            });
    </script>
</body>

</html>

Advantages of Fetch API

  • Modern and simpler than XMLHttpRequest.
  • Built-in support for handling promises.
  • Can handle errors easily using catch.

Reading JSON Data using XMLHttpRequest

XMLHttpRequest is an older, yet widely used method to read data from a URL or file. Although it has been mostly replaced by the Fetch API in modern applications. It's still useful in environments that do not support Fetch.

html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>Read JSON using XMLHttpRequest</title>
</head>

<body>
    <h2>Read JSON File</h2>

    <pre id="output"></pre>

    <script>
    
        // Create a new XMLHttpRequest object
        var xhr = new XMLHttpRequest();
        
        // Define the type of request and
        // the URL of the JSON file
        xhr.open('GET', 'data.json', true);
        
        // Define the onload function to handle
        // the data after receiving the response
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
            
                // Parse and display the JSON content
                var data = JSON.parse(xhr.responseText);
                document.getElementById('output').textContent
                    = JSON.stringify(data, null, 2);
            } else {
                console.error('Request failed with status', xhr.status);
            }
        };

        // Define what to do in case of error
        xhr.onerror = function () {
            console.error('Request failed');
        };
        
        // Send the request
        xhr.send();
    </script>
</body>

</html>

Reading Local JSON Files in Node.js using fs Module

If you're working in a Node.js environment, you can use the built-in fs (file system) module to read local files, including JSON files.

javascript
// Import the file system module
const fs = require('fs');
// Read the JSON file using the readFile method
fs.readFile('data.json', 'utf8', (err, jsonString) => {
   if (err) {
       console.error('Error reading file:', err);
       return;
   }
   try {
       // Parse the JSON content
       const data = JSON.parse(jsonString);
       console.log('Data:', data);
   } catch (err) {
       console.error('Error parsing JSON:', err);
   }
});
tools

JavaScript

Related Articles