In this tutorial, we will show you how to use jQuery’s getJSON method to fetch and display JSON array data.
Contents
JSON File Containing Array Data
JSON File Containing Array Data:test.json.
[
{"id":"01", "name":"Taro Tokyo", "birthday":"1981/01/20"},
{"id":"02", "name":"Jiro Saitama", "birthday":"1982/02/19"},
{"id":"03", "name":"Kenta Chiba", "birthday":"1983/03/18"},
{"id":"04", "name":"Shiro Kanagawa", "birthday":"1984/04/17"},
{"id":"05", "name":"Goro Yamanashi", "birthday":"1985/05/16"},
{"id":"06", "name":"Rokuro Shizuoka", "birthday":"1986/06/15"},
{"id":"07", "name":"Shichiro Fukuoka", "birthday":"1987/07/14"}
]
CSS for Displaying JSON Array Data
The following CSS is not critical, adjust as needed.
<style type="text/css">
<!--
body {
margin: 0px;
font-size:14px;
}
h1{
font-size:16px;
font-weight:normal;
line-height:1.4em;
text-align:center;
padding:15px 0;
}
#idWrap{
width:800px;
margin:0 auto;
}
#idJsonClk{
cursor:pointer;
margin:auto;
width:150px;
text-align:center;
padding:15px;
background-color:#666666;
color:#FFFFFF;
border:solid 1px #666666;
}
#idJsonClk:hover{
cursor:pointer;
margin:auto;
width:150px;
text-align:center;
padding:15px;
background-color:#FFFFFF;
color:#000000;
border:solid 1px #000000;
}
#idJsonArea{
margin:auto;
width:300px;
border:dotted 1px #333333;
padding:10px;
line-height:1.2em;
}
p{
padding:20px;
font-size:14px;
text-align:center;
}
-->
</style>
JavaScript for Fetching and Displaying JSON Array Data
Clicking on #idJsonClk will load the JSON file (test.json).
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#idJsonClk").click(function(){
var str_work="";
$.getJSON("test.json", function(json){
for(var i in json){
// Concatenate the information fetched from the test.json file
str_work=str_work+json[i].id+","+json[i].name+","+json[i].birthday+"<br>";
}
$("#idJsonArea").html(str_work);
});
});
});
</script>
HTML for Fetching and Displaying JSON Array Data
<div id="idWrap">
<h1>Click below to fetch and display the data from the JSON file(<a href="test.json" target="_blank">test.json</a>).</h1>
<div id="idJsonClk">Click Here</div>
<div id="idJsonArea">
Data fetched from the JSON format will be displayed here.
</div>
<!--/idJsonArea-->
</div>
Demo for Fetching and Displaying Array Data from JSON File
Click here for a demo page on fetching and displaying array data from a JSON file.
Please proceed at your own risk if you decide to reuse this. Do not reuse the Google Analytics tag inside the demo page tag.