Display JSON data using jquery/ajax

JSON¬†–¬†¬†Javascript Object Notation, is one of the beautiful techniques for parsing data. It’s beautiful primarily because it is light weight!

Here, I’m going to demonstrate how to display JSON data using ajax and jquery.

Let’s read some sample json data that is available in a file called json.test.js


[
 {
 "LinuxID":"1","LinuxDist":"Debian","Company":"Debian Project"<br>
 },
 {
 "LinuxID":"2","LinuxDist":"Ubuntu","Company":"Canonical Ltd."<br>
 },
 {
 "LinuxID":"3","LinuxDist":"Fedora","Company":"Fedora Project"<br>
 }
]

Now let’s write the html and javascript to display these results:

We call this file called displayjson.html:

<!DOCTYPE html>
<html>
<head>
<title>Display JSON data</title>
</head>
<body>
<div id="results"></div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.post("json.test.js",
function(data){
var obj=jQuery.parseJSON(data);
for(var i=0;i<obj.length;i++){
$("#results").append("Linux ID: "+obj[i].LinuxID).hide().fadeIn(500);
$("#results").append("<br>Linux Distribution: "+obj[i].LinuxDist).hide().fadeIn(500);
$("#results").append("<br>Company: "+obj[i].Company).hide().fadeIn(500);
$("#results").append("<br><hr>").hide().fadeIn(500);
}
});
});
</script>
</html>

 

Check out examples at Fun with JSON.
That’s it folks, enjoy!