I have this array:
JavaScript
x
6
1
var employees = [
2
{ "firstName":"John" , "lastName":"Doe" },
3
{ "firstName":"Anna" , "lastName":"Smith" },
4
{ "firstName":"Peter" , "lastName": "Jones" }
5
];
6
and I would like to print the entire array out as a html table. How would I accomplish this?
I tried this but could only get the final name the print:
JavaScript
1
24
24
1
<!DOCTYPE html>
2
<html>
3
<body>
4
<h2>Create Object from JSON String</h2>
5
<p>
6
First Name: <span id="fname"></span><br />
7
Last Name: <span id="lname"></span><br />
8
</p>
9
<script type="text/javascript">
10
var txt = '{"employees":[' +
11
'{"firstName":"John","lastName":"Doe" },' +
12
'{"firstName":"Anna","lastName":"Smith" },' +
13
'{"firstName":"Peter","lastName":"Jones" }]}';
14
15
var obj = eval ("(" + txt + ")");
16
17
for (i=0; i<txt.length; i++){
18
document.getElementById("fname").innerHTML=obj.employees[i].firstName
19
document.getElementById("lname").innerHTML=obj.employees[i].lastName
20
}
21
</script>
22
</body>
23
</html>
24
Advertisement
Answer
Using jQuery you can do:
JavaScript
1
26
26
1
var txt = '{"employees":[' +
2
'{"firstName":"John","lastName":"Doe" },' +
3
'{"firstName":"Anna","lastName":"Smith" },' +
4
'{"firstName":"Peter","lastName":"Jones" }]}';
5
6
// $.parseJSON will parse the txt (JSON) and convert it to an
7
// JavaScript object. After its call, it gets the employees property
8
// and sets it to the employees variable
9
var employees = $.parseJSON( txt ).employees;
10
11
var $table = $( "<table></table>" );
12
13
for ( var i = 0; i < employees.length; i++ ) {
14
var emp = employees[i];
15
var $line = $( "<tr></tr>" );
16
$line.append( $( "<td></td>" ).html( emp.firstName ) );
17
$line.append( $( "<td></td>" ).html( emp.lastName ) );
18
$table.append( $line );
19
}
20
21
$table.appendTo( document.body );
22
23
// if you want to insert this table in a div with id attribute
24
// set as "myDiv", you can do this:
25
$table.appendTo( $( "#myDiv" ) );
26
jsFiddle: http://jsfiddle.net/davidbuzatto/aDX7E/