Quantcast
Channel: web – Imran Tariq's Blog
Viewing all articles
Browse latest Browse all 33

Json array parsing in jquery

$
0
0

Here is a very simple code in parsing JSON using jQuery.

Suppose you have a JSON like this:

   {
		"userdata": [
			{
				"first":"Ciaran",
				"last":"Huber",
				"email":"elementum.purus@utdolordapibus.edu",
				"city":"Mayagüez"
			},
			{
				"first":"Hillary",
				"last":"Serrano",
				"email":"elit.pretium.et@scelerisquesedsapien.com",
				"city":"Martinsburg"
			}
		]
	}

This file makes the request to a php/Java or ASP etc file and displays the returned data into a table.
<html>
<head>
	<title>Parsing JSON Using jQuery</title>
	<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript">
	</script>
</head>
<body>
	<a href="#" id="loaduserdata">User Data</a>
	<table id="userdata" border="1">
		<thead>
			<th>First Name</th>
			<th>Last Name</th>
			<th>Email Address</th>
			<th>City</th>
		</thead>
		<tbody></tbody>
	</table>
	<script>
	$(document).ready(function(){
	});
	$("#loaduserdata").click(function(){
		$("#userdata tbody").html("");
		$.getJSON(
			"jsondata.php",
			function(data){
				$.each(data.userdata, function(i,user){
					var tblRow =
						"<tr>"
						+"<td>"+user.first+"</td>"
						+"<td>"+user.last+"</td>"
						+"<td>"+user.email+"</td>"
						+"<td>"+user.city+"</td>"
						+"</tr>"
					$(tblRow).appendTo("#userdata tbody");
				});
			}
		);
	});
	</script>
</body>
</html>

Share


Viewing all articles
Browse latest Browse all 33

Trending Articles