By using this method we can change the Json data into matrix table directly.
Approach 1:
- Take the JSON Object in a variable.
- Call a function which first adds the column names to the < table > element.(It is looking for the all columns, which is UNION of the column names).
- Traverse the JSON data and match key with the column name. Put the value of that key in the respective column.
- Leave the column empty if there is no value of that key.
<!DOCTYPE HTML>
<html>
<head>
<title>
How to convert JSON data to a
html table using JavaScript ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body style = "text-align:center;" id = "body">
<h1 style = "color:green;" >
Testing
</h1>
<p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;">
</p>
<button onclick = "constructTable('#table')">
click here
</button>
<br><br>
<table align = "center"
id="table" border="1">
</table>
<script>
var el_up = document.getElementById("GFG_UP");
var list = [
{ "col_1": "val_11", "col_3": "val_13" },
{ "col_2": "val_22", "col_3": "val_23" },
{ "col_1": "val_31", "col_3": "val_33" }
];
el_up.innerHTML = "Click on the button to create "
+ "the table from the JSON data.<br><br>"
+ JSON.stringify(list[0]) + "<br>"
+ JSON.stringify(list[1]) + "<br>"
+ JSON.stringify(list[2]);
function constructTable(selector) {
// Getting the all column names
var cols = Headers(list, selector);
// Traversing the JSON data
for (var i = 0; i < list.length; i++) {
var row = $('<tr/>');
for (var colIndex = 0; colIndex < cols.length; colIndex++)
{
var val = list[i][cols[colIndex]];
// If there is any key, which is matching
// with the column name
if (val == null) val = "";
row.append($('<td/>').html(val));
}
// Adding each row to the table
$(selector).append(row);
}
}
function Headers(list, selector) {
var columns = [];
var header = $('<tr/>');
for (var i = 0; i < list.length; i++) {
var row = list[i];
for (var k in row) {
if ($.inArray(k, columns) == -1) {
columns.push(k);
// Creating the header
header.append($('<th/>').html(k));
}
}
}
// Appending the header to the table
$(selector).append(header);
return columns;
}
</script>
</body>
</html>