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.

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

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

Output:

Read JSON File using JavaScript

JSON stands for JavaScript Object Notation. It’s a way of organizing data in a script file using text, making it easy to store and share data.

Reading JSON files, whether they’re stored locally or on a server, is crucial for web applications. In this tutorial, we’ll cover three methods for reading JSON files in JavaScript, which can be really helpful for web developers.

Table of Content

  • How to Read JSON file in JavaScript?
  • Using the fetch() API to read JSON file
  • Using the Require Module to read JSON file
  • By importing the Module to read JSON file
  • Conclusion

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.

Similar Reads

How to Read JSON file in JavaScript?

Three methods to read JSON files in JavaScript are:...

1. 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....

2. 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....

3. 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....

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....