If you've been rolling with html for sometime now, i believe the table element i.e. <table> is not new to you.
There are many ways of creating dynamic table. In this article, we would be looking at how we can achieve this using json. I.e. Converting json to html table.
I assume readers reading this have some basic undestanding of html, javascript and json.
Lets start by creating a table that shows the first and last names of three of our employees.
| Lastname | Firstname |
|---|---|
| John | Doe |
| Anna | Smith |
| Peter | Jones |
To achieve this in html, we use the markup:
<table border="1">
<tr>
<th>Lastname</th>
<th>Firstname</th>
</tr>
<tr>
<td>John </td>
<td>Doe</td>
</tr>
<tr>
<td>Anna </td>
<td>Smith</td>
</tr>
<tr>
<td>Peter</td>
<td>Jones</td>
</tr>
</table>
We can accomplish the same task using the json to html table way. Its just some javascript that loops throught the json data and append its value to a table.
<script>
//Here we assign the json data to a variable named employees.
var employees = [ { "firstName" : "John" , "lastName" : "Doe" }, { "firstName" : "Anna" , "lastName" : "Smith" }, { "firstName" : "Peter" , "lastName" : "Jones" }, ];
//Table's header. document.write("<table border='2'><tr><th>Lastname</th>");
document.write("<th>Firstname</th></tr>");
//Loop and append
for(i=0; i<employees.length; i++){
document.write("<tr><td>"+employees[i].firstName+"</td><td>"+employees[i].lastName+"</td>");
document.write("</tr>");
}
document.write("</table>");
</script>
The above javascript will give the same table. I.e.
You can use this single javascript in multiple pages.
This comes in when you want to display the same table in multiple pages.
Just put the script in a .js file, and link it to the pages you want it displayed. Just like css.
<script src="mytable.js"></script>
More data can also be added to the employees json object.
What makes this json to html way dynamic is the fact that json is a data format just like xml.
Data can be dynamic(change).
So converting dynamic json to a neater tabled format is not a bad idea.
Many apis are now adapting the json format also.
E.g the google direction api which is dynamic i.e. It changes.
It could go a bit more complex, but this article was written to give/show the basics of how the conversion of json data to html table can be done.
Thanks for reading
God bless!
http://davolu.blogspot.com
No comments:
Post a Comment