How to convert JSON data to a html table using JavaScript/jQuery ?
Last Updated :
19 Sep, 2024
To convert JSON data into an HTML table, there are multiple approaches, each of which has its own strengths. Let's walk through both approaches you mentioned, detailing how each one works.
Approach 1: Using for loop
- Take the JSON Object in a variable.
- Call a function that first adds the column names to the < table > element. (It is looking for all columns, which is the UNION of the column names).
- Traverse the JSON data and match the 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.
Example: This example implements the for-loop approach.
HTML
<!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;">
GeeksForGeeks
</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>
let el_up = document.getElementById("GFG_UP");
let 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
let cols = Headers(list, selector);
// Traversing the JSON data
for (let i = 0; i < list.length; i++) {
let row = $('<tr/>');
for (let colIndex = 0; colIndex < cols.length; colIndex++) {
let 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) {
let columns = [];
let header = $('<tr/>');
for (let i = 0; i < list.length; i++) {
let row = list[i];
for (let 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>
Output:
OutputApproach 2: Using JSON.stringify() method
- Store the JSON object into the variable. and first put all keys in a list.
- Create an element <table> and a <tr> element for the header of the table.
- Visit the keys list and create a <th> for each value and insert it into the <tr> element created for the header.
- Then, for every entry in the object, create a cell and insert it to the particular row.
- Leave the column empty if there is no value of that key.
Example: This example implements the JSON.stringify() method approach.
HTML
<!DOCTYPE HTML>
<html>
<head>
<title>
How to convert JSON data to a html
table using JavaScript/jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
</p>
<button onclick="GFG_FUN()">
click here
</button>
<br><br>
<table id="table" align="center" border="1px"></table>
<script>
let el_up = document.getElementById("GFG_UP");
let list = [
{
"col_1": "val_11", "col_2": "val_12",
"col_3": "val_13"
},
{
"col_1": "val_21", "col_2": "val_22",
"col_3": "val_23"
},
{
"col_1": "val_31", "col_2": "val_32",
"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 GFG_FUN() {
let cols = [];
for (let i = 0; i < list.length; i++) {
for (let k in list[i]) {
if (cols.indexOf(k) === -1) {
// Push all keys to the array
cols.push(k);
}
}
}
// Create a table element
let table = document.createElement("table");
// Create table row tr element of a table
let tr = table.insertRow(-1);
for (let i = 0; i < cols.length; i++) {
// Create the table header th element
let theader = document.createElement("th");
theader.innerHTML = cols[i];
// Append columnName to the table row
tr.appendChild(theader);
}
// Adding the data to the table
for (let i = 0; i < list.length; i++) {
// Create a new row
trow = table.insertRow(-1);
for (let j = 0; j < cols.length; j++) {
let cell = trow.insertCell(-1);
// Inserting the cell at particular place
cell.innerHTML = list[i][cols[j]];
}
}
// Add the newly created table containing json data
let el = document.getElementById("table");
el.innerHTML = "";
el.appendChild(table);
}
</script>
</body>
</html>
Output:
OutputBoth approaches are effective for converting JSON data to an HTML table. Depending on your needs and complexity of data, either approach can be used.
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Similar Reads
How to Convert HTML Table to JSON in JavaScript? HTML tables are commonly used to present structured data on websites. In many scenarios, this tabular data needs to be converted to JSON format for processing, storage, or server communication. We will discuss different approaches to converting HTML tables to JSON using JavaScript.These are the foll
3 min read
How to export HTML table to CSV using JavaScript ? Comma Separated Values or CSV is a type of text file where each value is delimited by a comma. CSV files are very useful for the import and export of data to other software applications.Sometimes while developing web applications, you may come into a scenario where you need to download a CSV file co
6 min read
How to Convert HTML Form Field Values to JSON Object using JavaScript? Storing HTML input data into JSON format using JavaScript can be useful in various web development scenarios such as form submissions, data processing, and AJAX requests. Here we will explore how to convert the HTML form input data into the JSON format using JavaScript. ApproachThe HTML file contain
2 min read
How to Convert Blob Data to JSON in JavaScript ? When dealing with Blob data in JavaScript, such as binary data or files, we may need to convert it into JSON format for doing so JavaScript provides us with various methods as listed below. Table of Content Using FileReader APIUsing TextDecoder APIUsing FileReader APIIn this approach, we first use t
2 min read
How to Convert HTML to JSON in JavaScript ? Converting HTML to JSON is important for structured data extraction and integration with JavaScript applications. Here, we will learn different approaches to converting HTML to JSON in JavaScript. Below are the approaches to convert html to JSON in JavaScript: Table of Content Using html-to-json Lib
2 min read