Fetch JSON Array Elements Using jQuery AJAX Method: getJSON

Advertisement:

Video tutorial illustrates the extraction of JSON Array elements using jQuery AJAX method: getJSON

Here we extract data(JSON ARRAY) from an external JSON file, which has a file extension .json

HTML code
index.html

1
2
3
4
5
6
7
8
<html>
<head><title>Fetch JSON array Data</title></head>
<body>
<ul></ul>
<script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="script/my_script.js"></script>
</body>
</html>

Here we have a unordered list. We’ll be filling it’s list items from the JSON file using jQuery.

JSON File
json_data.json

1
2
3
4
5
6
{
 "person": [  
     { "name": "Satish", "age": 25 },
     { "name": "Shwetha", "age": 24 }
 ]
}

Here we have a key called “person”, which is a JSON array.
“person” has two elements in it, which are objects.
Each object has two key => value pairs.
The key being, name and age.

jQuery Code
my_script.js

1
2
3
4
5
6
7
8
$(document).ready( function() {
 $.getJSON("json_data.json", function(data){
       $.each(data.person, function(){
	         $("ul").append("<li>Name: "+this['name']+"</li>
                                <li>Age: "+this['age']+"</li>
                                <br />");
	   });
 });

Once the document loads, we call an anonymous function. Inside that, we call the shortcut function of jQuery AJAX method i.e., $.getJSON method.
The first parameter is the file to be parsed, second parameter is the callback function.

Inside the callback function, we loop through the array elements and fetch the values using its key names, and finally append it to the unordered list of index.html

Fetch JSON Array Elements Using jQuery AJAX Method: getJSON


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=VAMz-fcDNhs [Watch the Video In Full Screen.]



To make the AJAX effect, you could write the jQuery coding inside a custom function and then call it for setTimeout() function etc:
setTimeout(customFunction, 4000);
setInterval(repeatFunctionCall, 4000);
slideDown().delay(4000).slideUp(); ( Chain method )

Advertisements

1 thought on “Fetch JSON Array Elements Using jQuery AJAX Method: getJSON”

Leave a Reply

Your email address will not be published. Required fields are marked *