How to read from a JSON file using AJAX

Rumman Ansari   Software Engineer   2023-03-26   161 Share
☰ Table of Contents

Table of Content:


How to read from a JSON file using AJAX

Now let us see how to read from a JSON file using AJAX. JSON consist of text, it can be converted into javascript object using JSON.parse() method


var request= new XMLHttpRequest();
request.open('GET','example.json',true);
request.send();
request.onreadystatechange = function() {
 if(request.readyState == 4 && request.status == 200){
 var item= JSON.parse(request.responseText)
}
};

Here the variable item has a array of javascript objects where each object has a key value pair from the JSON file. Now you can loop through these object to read the data and use it to update DOM.

Explanation

  • var request= new XMLHttpRequest();: This line creates a new instance of the XMLHttpRequest object, which is used to make an HTTP request.
  • request.open('GET','example.json',true);: This line sets up the request by specifying the HTTP method (GET), the file to be retrieved (example.json), and whether the request should be made asynchronously (true).
  • request.send();: This line sends the request to the server.
  • request.onreadystatechange = function() {: This line sets up a function to be called whenever the ready state of the request changes. The ready state of the request indicates the status of the request, such as whether the request has been sent and whether the response has been received.
  • if(request.readyState == 4 && request.status == 200){: This line checks whether the ready state of the request is 4 (meaning the request is complete) and the status of the request is 200 (meaning the request was successful).
  • var item= JSON.parse(request.responseText): If the request was successful, this line takes the response text from the request and parse it to JSON object.

var list = '<ul>';
for(var i in item)
{
list += '<li>'+item[i].name+'</li>';
}

"var list = '<ul>';" This line creates a variable named "list" and assigns an opening unordered list element "<ul>" to it as a string.

"for(var i in item)" This line initiates a for-in loop that iterates through the "item" object. "var i" declares a variable "i" that will store the current property name of the object being accessed.

"list += '<li>'+item[i].name+'</li>';" This line is executed during each iteration of the loop. It appends a new list item element "<li>" followed by the value of the "name" property of the current object, and a closing list item element "</li>" to the "list" variable.

Finally, the "list" variable would contain an HTML string with a list of items.