In this article I will explain with an example, how convert HTML Table data to JSON using JavaScript.
HTML Markup
The following HTML Markup consists of an HTML Table and an HTML Button.
The Button has been assigned a JavaScript OnClick event handler which calls the Convert JavaScript function.
<table id="tblCustomers" cellspacing="0" cellpadding="0">
<tr>
<th>Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td>1</td>
<td>John Hammond</td>
<td>United States</td>
</tr>
<tr>
<td>2</td>
<td>Mudassar Khan</td>
<td>India</td>
</tr>
<tr>
<td>3</td>
<td>Suzanne Mathews</td>
<td>France</td>
</tr>
<tr>
<td>4</td>
<td>Robert Schidner</td>
<td>Russia</td>
</tr>
</table>
<hr/>
<input type="button" id="btnSubmit" value="Submit" onclick="Convert()" />
JavaScript function to convert HTML Table to JSON
When the Submit Button is clicked, the Convert JavaScript function is called.
Inside the Convert JavaScript function, the HTML Table is referenced using the document.getElementById JavaScript function.
Then, a loop will be executed over the HTML Table Header cells and the cell values are copied to an Array.
And then, another loop is executed over the HTML Table rows. Inside each row a child loop is executed over the cells and copied to a JavaScript object which is later added to a JavaScript Array.
Finally, the JavaScript Array is converted into a JSON string and displayed in JavaScript Alert Message Box.
<script type="text/javascript">
function Convert() {
var table = document.getElementById("tblCustomers");
var header = [];
var rows = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
header.push(table.rows[0].cells[i].innerHTML);
}
for (var i = 1; i < table.rows.length; i++) {
var row = {};
for (var j = 0; j < table.rows[i].cells.length; j++) {
row[header[j]] = table.rows[i].cells[j].innerHTML;
}
rows.push(row);
}
alert(JSON.stringify(rows));
}
</script>
Screenshots
The HTML Table
The converted JSON
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads