BACK
TOP
Create HTML Table from JSON
Matías Creimerman - Buenos Aires, Argentina - 2017-11-05
You can use this function to create a HTML table from JSON data:


HTML:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script> <div id="container"></div>


CSS:
.tableStyle{width: 100px;border: 1px solid black;}.tableStyle th{color: red;}


JSON:
var json = [{id: 1, name: 'Carlitos', age: 30}, {id: 2, name: 'Miguel', age: 32}, {id: 3, name: 'Amanda', age: 35}];


JS:
createTableFromJson('container', json, true, 'tableStyle'); function createTableFromJson(containerID, json, withHeader, cssName){ var table = $('<table>'); table.addClass(cssName); $.each(json, function(k, v) { var o = json[k]; var row = $('<tr>'); $.each(o, function(a, b) { if (withHeader && k == 0){ var head = $('<th>'); head.text(a); table.append(head); } var cell = $('<td>'); cell.text(b); row.append(cell); }); table.append(row); }); $('#' + containerID).append(table); }

CODE jsfiddle FULL SAMPLE

This content is property of Matias Creimerman
Any misuse of this material will be punishable
This work is licensed under a
Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License
Creative Commons License