Html Table To Json Using Javascript

In this article, I will explain about to convert Html table data to JSON format using Javascript. So let’s start.

Html Code

The following HTML code contains the table and one button. Once you click on the button, the click event will be triggered and it will call the ConvertToJson function.

<table id="myTbl" cellspacing="0"  cellpadding="0" class="table table-hover table-striped">
      <tr>
          <th>Id</th>
          <th>Name</th>
      </tr>
      <tr>
          <td>1</td>
          <td>Chand Dakhara</td>
      </tr>
      <tr>
          <td>2</td>
          <td>Nishan Kakadiya</td>
      </tr>
      <tr>
          <td>3</td>
          <td>Shailja Jariwala</td>
      </tr>
  </table>
  <input type="button" id="btnSubmit" value="Submit" onclick="ConvertToJson()" />

Script

function ConvertToJson() {
    debugger
        var tbl = document.getElementById("myTbl");
        var header = [];
        var rows = [];
 
        for (var i = 0; i < tbl.rows[0].cells.length; i++) {
            header.push(tbl.rows[0].cells[i].innerHTML);
        }
 
        for (var i = 1; i < tbl.rows.length; i++) {
            var row = {};
            for (var j = 0; j < tbl.rows[i].cells.length; j++) {
                row[header[j]] = tbl.rows[i].cells[j].innerHTML;
            }
            rows.push(row);
        }
 
        alert(JSON.stringify(rows));
    }

Output

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories