Click here to Skip to main content
16,017,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to read the JsonData.json file below and populate my html table in javascript:

{
"ID": 1,
"Name": "John Smith",
"IDNumber": "7606015012088"
},
{
"ID": 2,
"Name": "Molly Malone",
"IDNumber": "8606125033087"
},


Please help as I am very new to javascript.
My html is:

XML
script src="jquery-1.10.2.min.js"></script>

<script type="text/javascript">

</script>





</head>
<body>
<h1>A JavaScript Test</h1>
<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>ID Number</th>
    </tr>
</table>
<p>

<button>Load Data</button>
Posted

1 solution

Hi,

First of all, your JSON file is not proper. It should be like this.

HTML
[{
"ID": 1,
"Name": "John Smith",
"IDNumber": "7606015012088"
},
{
"ID": 2,
"Name": "Molly Malone",
"IDNumber": "8606125033087"
}]

Consider following code snippet. It will load a json file called 'jsondata.json' and creates a table.
JavaScript
<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
	<script>
		function onLoad(){
			var url='jsondata.json';
			$.getJSON(url, function(json){
				var table = $('<table>');
				table.attr('border','1');
				var tr = $('<tr>');
				var td = $('<td>');
				td.html("ID");
				tr.append(td);
				td = $('<td>');
				td.html('Name');
				tr.append(td);
				td = $('<td>');
				td.html('IDNumber');
				tr.append(td);
				table.append(tr);
				for( var i=0; i<json.length;i++){
					var tr = $('<tr>');
					var td = $('<td>');
					td.html(json[i].ID);
					tr.append(td);
					td = $('<td>');
					td.html(json[i].Name);
					tr.append(td);
					td = $('<td>');
					td.html(json[i].IDNumber);
					tr.append(td);
					table.append(tr);
				}
				$('body').append(table);
			});
		}
	</script>
</head>
<body  önload ="onLoad();">
</body>
</html>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900