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 a File in Next.js?
Loading Data from files consists of using client-side techniques to read and process files in a Next.js application. In this article, we will explore a practical demonstration of Load Data from a File in Next.js. We will load a validated CSV input file and display its contents in tabular format. App
3 min read
How to post a file from a form with Axios?
In this article, we are going to discuss making POST requests with form data using the Axios library. Axios is a Promise based HTTP client that can be used for the web as well as for Node.JS development. However, in this article, we are going to strictly refer to client-side use of Axios. To start o
3 min read
How to fetch data from a local JSON file in React Native ?
Fetching JSON (JavaScript Object Notation) data in React Native from Local (E.g. IOS/Android storage) is different from fetching JSON data from a server (using Fetch or Axios). It requires Storage permission for APP and a Library to provide Native filesystem access. Implementation: Now letâs start w
4 min read
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
4 min read
How to work with Node.js and JSON file ?
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging d
4 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 load data from nested arrays in DataTables ?
DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for a webpage. It is a very simple-to-use plug-in with a variety of options for the developerâs custom changes as per the application need. The pluginâs features include pagination, sorting, searching,
4 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
3 min read