How to load a JSON object from a file with ajax?
Last Updated :
25 Apr, 2024
Loading a JSON object from a file using AJAX involves leveraging XMLHttpRequest (XHR) or Fetch API to request data from a server-side file asynchronously. By specifying the file's URL and handling the response appropriately, developers can seamlessly integrate JSON data into their web applications. This method enables dynamic loading of data without requiring a page refresh, facilitating responsive and interactive user experiences.
JSON (JavaScript Object Notation) is a simple and lightweight format used to exchange data between servers and different parts of an application. It is easy for both humans and machines to understand and execute. With its simplified and structured approach, JSON makes sending and retrieving data between client and server sides easy.
Approaches
AJAX Approaches:
- Using XMLHttpRequest (XHR): This is a basic AJAX approach.
- Using Fetch API: Fetch API is a modern replacement of XHR but still is an AJAX based approach.
- Using JQuery: provides a simplified AJAX based approach using '$'.
- Using Axios: Axios is an another important library for making AJAX requests.
Non-AJAX Approaches:
- Using Node.js: This is mainly for server side javaScript using Node.js that does not involve the communication with client side via HTTP.
example.json File
{
"website": "GeeksForGeeks",
"articles": [
{
"title": "How to access props inside a functional component",
"author": "mathivananshivam",
"published_date": "27-02-2024",
"url": "https://www.geeksforgeeks.org/how-to-access-props-inside-a-functional-component/"
},
{
"title": "Power Spectral Density",
"author": "mathivananshivam",
"published_date": "28-02-2024",
"url": "https://www.geeksforgeeks.org/power-spectral-density/"
},
{
"title": "Why we need Redux in React?",
"author": "mathivananshivam",
"published_date": "14-03-2024",
"url": "https://www.geeksforgeeks.org/why-we-need-redux-in-react/"
}
]
}
Using XMLHttpRequest (XHR)
Using XMLHttpRequest (XHR) involves creating a new instance of XMLHttpRequest, specifying the file URL and request method (typically 'GET'), and setting up event handlers to handle the response asynchronously. This approach allows for direct control over the AJAX request and is suitable for scenarios where a lightweight solution is preferred or when working without additional libraries.
Example: Implementation to show how to load a JSON object from a file with ajax.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>JSON Fetch</title>
<style>
pre {
background-color: #f4f4f4;
border: 1px solid #ddd;
padding: 10px;
overflow-x: auto;
font-family: monospace;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>JSON Data</h1>
<div id="json-container">
<!-- Parsed JSON data will be displayed here -->
</div>
<script>
let xhr = new XMLHttpRequest();
xhr.open('GET', 'example.json', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let jsonObject =
JSON.parse(xhr.responseText);
displayJSON(jsonObject);
}
};
xhr.send();
function displayJSON(jsonObject) {
let jsonContainer =
document.getElementById('json-container');
let pre =
document.createElement('pre');
pre.textContent = JSON.stringify(jsonObject, null, 2);
jsonContainer.appendChild(pre);
}
</script>
</body>
</html>
Output:

Using JQuery
Using jQuery AJAX involves calling the $.ajax()
function, specifying the URL and data type (e.g., 'json'), and defining a success callback function to handle the response. This approach abstracts away complexities, providing a simpler syntax and compatibility across different browsers, making it convenient for developers familiar with jQuery.
Example: Implementation to show how to load a JSON object from a file with ajax.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>JSON Fetch Example</title>
<!-- Include jQuery library -->
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
<style>
pre {
background-color: #f4f4f4;
border: 1px solid #ddd;
padding: 10px;
overflow-x: auto;
font-family: monospace;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>JSON Data</h1>
<div id="json-container">
<!-- Parsed JSON data will be displayed here -->
</div>
<script>
$.getJSON('example.json', function (data) {
displayJSON(data);
});
function displayJSON(jsonObject) {
let jsonContainer =
document.getElementById('json-container');
let pre = document.createElement('pre');
pre.textContent = JSON.stringify(jsonObject, null, 2);
jsonContainer.appendChild(pre);
}
</script>
</body>
</html>
Output:

Similar Reads
How to load data from JSON into a Bootstrap Table? This article describes how a Bootstrap Table is created using a given JSONÂ data. The data can be retrieved by either importing it or representing it in JavaScript. The following are given two methods to do it. Displaying JSON data without importing any file: The JSON file that has to be read can be
4 min read
How to Read JSON Files with Pandas? JSON (JavaScript Object Notation) store data using key-value pairs. Reading JSON files using Pandas is simple and helpful when you're working with data in .json format. There are mainly three methods to read Json file using Pandas Some of them are:Using pd.read_json() MethodUsing JSON Module and pd.
2 min read
How to Import a JSON File to a Django Model? In many web development projects, it's common to encounter the need to import data from external sources into a Django application's database. This could be data obtained from APIs, CSV files, or in this case, JSON files. JSON (JavaScript Object Notation) is a popular format for structuring data, an
3 min read
How to read/write JSON File? Ruby is a dynamic, object-oriented programming language developed by Yukihiro Matsumoto in the mid-1990s. Its key features include a simple and elegant syntax, dynamic typing, object-oriented nature, support for mixins and modules, blocks and closures, metaprogramming, and a vibrant community with a
6 min read
How to read and write JSON file using Node ? Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises.JSON(JavaScript Object Notation) is a simple and t
3 min read
How to Add Data in JSON File using Node.js ? JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article.Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
How to Read and Parse Json File with RapidJson? RapidJSON is a high-performance JSON library for C++. It provides a fast and easy-to-use interface for parsing and generating JSON. It is small but complete. It supports both SAX and DOM style API. Also, it is self-contained and header-only. It does not depend on external libraries such as BOOST. It
5 min read
How to Convert a JSON File to Microsoft Excel? JSON file is used to store human-provided text & then it will eventually convert it to a computer-readable file. The JSON file can't be readable and that's why it is often converted to an Excel file that is readable. That's why procedural steps must be followed to easily convert the JSON file to
3 min read
How to read this JSON file with jsonlite in R? JSON data is represented as key-value pairs, which are similar to the concept of a dictionary in Python or a list of named elements in R. In this article, we will learn how to access different components of a JSON file using R. What is jsonlite package in R? The jsonlite package in R provides an eas
2 min read
Postman - How to Sent .json File as POST Data Payload within Pre-request Script? Postman is quite a popular tool that is primarily used for API testing. There are various features in this including sending different kinds of requests to the web servers and getting the responses in real time. In this article, we will be focusing on how to use the Postman to send .json files as PO
3 min read