Open In App

Read JSON File using JavaScript

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data.

Reading JSON data files (local or from a server) is very important while building web applications. Many web developers face issues while dealing with JSON files, so in this tutorial, we have explained three methods to read JSON files in JavaScript.

NOTE: JavaScript supports JSON internally so it does not require additional modules to import and display the JSON. We just have to import the JSON file and can easily use it directly to perform manipulations on it.

How to Read JSON file in JavaScript?

Three methods to read JSON files in JavaScript are:

Note: The below JSON file will be used to fetch the data.

sample.json

{
  "users":[
    {
        "site":"GeeksforGeeks",
        "user": "Shobhit"
    }
  ]
}

Using the fetch() API to read JSON file

The fetch() method is used to read JSON files (local or uploaded files). It uses the same syntax for both file types.

Syntax

fetch('JSONFilePath').then().then().catch();

Follow these steps to read the JSON file using the fetch API method:

  • Create a JSON file and add data to it
  • Open the JavaScript file
  • In the fetch method pass the path of the JSON file
  • Use the .json() method to parse the data in JSON format.
  • Display the content in the console.

Example of Reading JSON file in JavaScript:

The below code will help you understand the use of the fetch() method to Read JSON files.

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 File</title>
</head>
<body>
    <h1>GeeksforGeeks</h1>
    <h3>
        Go to the console to see the
        fetched data!!
    </h3>
    <script>
        function fetchJSONData() {
            fetch("./sample.json")
                .then((res) => {
                    if (!res.ok) {
                        throw new Error
                            (`HTTP error! Status: ${res.status}`);
                    }
                    return res.json();
                })
                .then((data) =>
                      console.log(data))
                .catch((error) =>
                       console.error("Unable to fetch data:", error));
        }
        fetchJSONData();
    </script>
</body>
</html>


Output:

console view of JSON data after fetch API

Using the Require Module to read JSON file

Require module is used to include modules in your application. It can be used to include a file in a web application.

Syntax:

require(JSONFilePath);

Follow these steps to read JSON files using the required module in JavaScript.

  • Create the JSON file as specified in the previous approach
  • Create a script.js and use the required method of the node to import the JSON file
  • Print the data on the console

NOTE: Instead of running the program on the browser we will run it on the console using Node. Make sure you have at least Node version 17.0.

Example

The below code can be directly pasted in a script file(node must be installed) to execute and fetch the JSON data.

Javascript




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


Output:

{ users: [ { site: 'GeeksForGeeks', user: 'Shobhit' } ] }

By importing the Module to read JSON file

The import statement can be used to import and store JSON file elements into a variable in JavaScript.

Syntax:

import nameOfVariable from "JSONFilePath" assert {type: 'json'};
  • Create the JSON file as described in the previous examples.
  • Create a script.js file and import the JSON file

Example of Reading JSON file in JavaScript:

The below code Reads the JSON file by importing it using the import statement.

Javascript




// script.js
import user from "./sample.json" assert { type: 'json' };
console.log(user)


HTML




<!-- index.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 File</title>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
    <h3>
        Go to the console to see the
        fetched data!!
    </h3>
    <script type="module" src="./script.js"></script>
</body>
 
</html>


Output:

console view of JSON data using import module

Conclusion

Reading JSON files in JavaScript is a very important task for a web developer as JSON files are used to store user data, configuration data, static data, and other vital information.

This guide explained three methods to read JSON files in JavaScipt with examples. By understanding these techniques, developers can confidently tackle JSON file-related tasks, ensuring smoother development processes and enhanced user experiences.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads