I am using jquery data table. I have a table like below,
<table id="employees">
  <thead>
     <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
      </tr>
    </thead>
   <tbody>
      <tr>
           <td>1</td>
           <td>Karthik</td>
           <td>[email protected]</td>
           <td>1234</td>
       </tr>
       <tr>
           <td>1</td>
           <td>Karthik</td>
           <td>[email protected]</td>
           <td>1234</td>
       </tr>
     </tbody>
</table>
I am converting the table into jquery datatable as $('#employees').DataTable()
I want to convert my jquery datatable as json format. Please help me to convert this as
[{"Id":"1", "Name":"Karthik","Email":"[email protected]","Phone":"1234"}]
                Try using DataTable rows function
 $('#YourDataTableID').DataTable().rows( { search: 'applied' } ).data().toArray();
                        Try this
$(document).ready(function(){
   // Let's put this in the object like you want and convert to JSON (Note: jQuery will also do  this for you on the Ajax request)
   alert(JSON.stringify(tableToJSON($("#employees"))));
});
function tableToJSON(tblObj){  
   var data = [];
   var $headers = $(tblObj).find("th");
   var $rows = $(tblObj).find("tbody tr").each(function(index) {
   $cells = $(this).find("td");
   data[index] = {};
   $cells.each(function(cellIndex) {
     data[index][$($headers[cellIndex]).html()] = $(this).html();
   });    
});
  return data;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="employees">
  <thead>
     <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
      </tr>
    </thead>
   <tbody>
      <tr>
           <td>1</td>
           <td>Karthik</td>
           <td>[email protected]</td>
           <td>1234</td>
       </tr>
       <tr>
           <td>2</td>
           <td>Karthik</td>
           <td>[email protected]</td>
           <td>4567</td>
       </tr>
     </tbody>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With