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