Read JSON File Using JavaScript
Last Updated :
18 Oct, 2024
To read a JSON file using JavaScript, you have several options depending on the environment you’re working in. In JavaScript, reading a JSON file involves converting the JSON content into a JavaScript object or array for easy manipulation.
This can be done in the browser with fetch() or in Node.js using fs.readFile() or require(). After fetching, use JSON.parse() to convert the data into a JavaScript object.
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.
Reading JSON files in JavaScript is important for managing data in web applications. To learn how to handle JSON data efficiently in full-stack apps, the Full Stack Development with Node JS course provides practical examples of working with JSON on both the client and server sides.
How to Read JSON files 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"
}
]
}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.
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: 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:

fetch() API to Read JSON file
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.
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' } ] }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.
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: 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>GeeksforGeeks</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:

importing the Module to read JSON file
Read JSON File Using JavaScript – FAQs
What is the fetch() API and how is it used to read JSON files?
The fetch() API is used to make network requests. To read a JSON file, use fetch(‘path/to/file.json’).then(response => response.json()) to parse and access the data.
How do I read a local JSON file using JavaScript?
In a browser, you can use the fetch() API. In Node.js, use fs.readFileSync() or require() to read local JSON files.
Can I use the require function to read JSON files in JavaScript?
Yes, in Node.js, you can use require(‘./path/to/file.json’) to read and import JSON files directly as JavaScript objects.
How do I handle errors when reading JSON files in JavaScript?
Use .catch() with fetch() to handle errors, or try-catch blocks in Node.js when using require() or fs.readFile().
Can I read JSON files using the import statement in JavaScript?
Yes, in modern JavaScript (ES6+), you can use the import statement with assert {type: ‘json’} to import JSON files directly.
Similar Reads
Read JSON File Using JavaScript
To read a JSON file using JavaScript, you have several options depending on the environment you're working in. In JavaScript, reading a JSON file involves converting the JSON content into a JavaScript object or array for easy manipulation. This can be done in the browser with fetch() or in Node.js u
4 min read
How to read a local text file using JavaScript?
Reading a local text file involves accessing the contents of a file stored on a user's device. Using JavaScript, this can be achieved with the HTML5 File API and the FileReader object, which reads files selected through an <input> element or drag-and-drop, asynchronously. Getting Started with
4 min read
How to read a local text file using JavaScript?
Reading a local text file involves accessing the contents of a file stored on a user's device. Using JavaScript, this can be achieved with the HTML5 File API and the FileReader object, which reads files selected through an <input> element or drag-and-drop, asynchronously. Getting Started with
4 min read
JavaScript- Edit a CSV File using JS
If you want to edit a CSV file using JavaScript, you can use the following methods depending on your environment (browser or Node.js). 1. Editing CSV in the BrowserIf you're working with a CSV file in the browser, you can use JavaScript to manipulate the CSV data (after converting it into a readable
3 min read
JavaScript- Edit a CSV File using JS
If you want to edit a CSV file using JavaScript, you can use the following methods depending on your environment (browser or Node.js). 1. Editing CSV in the BrowserIf you're working with a CSV file in the browser, you can use JavaScript to manipulate the CSV data (after converting it into a readable
3 min read
Convert XML to JSON using JavaScript
Convert XML to JSON effortlessly using JavaScript, enabling seamless integration and manipulation of XML data within your applications. JavaScript libraries like xml-js and xmldom Library simplify the conversion process, ensuring compatibility and efficiency. Below are the approaches to convert XML
2 min read
JavaScript Program to read text File
Given a text file, write a JavaScript program to extract the contents of that file. There is a built-in Module or in-built library in NodeJs that handles all the reading operations called fs (File-System). It is basically a JavaScript program (fs.js) where a function for reading operations is writte
2 min read
JavaScript Program to read text File
Given a text file, write a JavaScript program to extract the contents of that file. There is a built-in Module or in-built library in NodeJs that handles all the reading operations called fs (File-System). It is basically a JavaScript program (fs.js) where a function for reading operations is writte
2 min read
How to Parse JSON in JavaScript ?
Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipula
2 min read
JavaScript JSON parse() Method
The JSON.parse() method is used to convert a JSON string into a JavaScript object. It’s become important when dealing with data in JSON format, interacting with APIs, or storing data in the browser. It converts a JSON string into a JavaScript object.Throws a SyntaxError if the input string is not va
4 min read
JavaScript JSON parse() Method
The JSON.parse() method is used to convert a JSON string into a JavaScript object. It’s become important when dealing with data in JSON format, interacting with APIs, or storing data in the browser. It converts a JSON string into a JavaScript object.Throws a SyntaxError if the input string is not va
4 min read
JavaScript JSON Complete Reference
JavaScript JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It is easy to read, write, and parse. JSON is based on key-value pairs and arrays. [GFGTABS] JavaScript let data = '{"name":"Raj","age":25}'; let obj = JSON.par
1 min read
JavaScript JSON Complete Reference
JavaScript JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It is easy to read, write, and parse. JSON is based on key-value pairs and arrays. [GFGTABS] JavaScript let data = '{"name":"Raj","age":25}'; let obj = JSON.par
1 min read
JSON vs JavaScript Object
JSON (JavaScript Object Notation) and JavaScript Objects are important for handling data in JavaScript, but they serve different purposes. JSON is a lightweight data format for transferring data, while JavaScript Objects are in-program data structures used for manipulation and logic. What is JSON?JS
3 min read
JSON vs JavaScript Object
JSON (JavaScript Object Notation) and JavaScript Objects are important for handling data in JavaScript, but they serve different purposes. JSON is a lightweight data format for transferring data, while JavaScript Objects are in-program data structures used for manipulation and logic. What is JSON?JS
3 min read
How to Pretty Print JSON String in JavaScript?
To pretty print JSON, you can format JSON strings with proper indentation, making them easy to read and debug. In JavaScript, you can achieve this using JSON.stringify() with optional parameters to specify the indentation level. Pretty printing JSON adds line breaks and spaces for readability.It is
3 min read
How to Pretty Print JSON String in JavaScript?
To pretty print JSON, you can format JSON strings with proper indentation, making them easy to read and debug. In JavaScript, you can achieve this using JSON.stringify() with optional parameters to specify the indentation level. Pretty printing JSON adds line breaks and spaces for readability.It is
3 min read
JavaScript | Remove a JSON attribute
In this article, we will see how to remove a JSON attribute from the JSON object. To do this, there are few of the mostly used techniques discussed. First delete property needs to be discussed. Delete property to Remove a JSON Attribute This keyword deletes a property from an object: This keyword de
2 min read
Explain about Read and Write of a file using JavaScript
Handling file operations such as reading and writing is a common requirement in many JavaScript applications, especially on the server side using Node.js. This article explains how to perform these operations using Node.js's built-in fs (File System) module. The fs ModuleThe fs module provides an AP
3 min read