Haroldas
Haroldas

Reputation: 1010

parse html table to json jquery

how to convert html table to json data? i need result like this. Code must be on jquery

{"status":"ok","data":[{"name":"Haroldas","number":444,"address":"address"},{"name":"tom","number":999,"address":"rrr"},{"name":"ted","number":333,"address":"kkk"}]}

here is my table:

<table id="excel">
  <thead>
    <tr role="row">
      <th>name</th>
      <th>number</th>
      <th>address</th>
    </tr>
  </thead>
  <tbody>
    <tr role="row" class="odd">
      <td class="sorting_1">Haroldas</td>
      <td>444</td>
      <td>address</td>
    </tr>
    <tr role="row" class="even">
      <td class="sorting_1">ted</td>
      <td>333</td>
      <td>kkk</td>
    </tr>
    <tr role="row" class="odd">
      <td class="sorting_1">tom</td>
      <td>999</td>
      <td>rrr</td>
    </tr>
  </tbody>
</table>

EDIT: here is jquery code, but not exactly because in table are thead

$.makeTableToArray = function () {
    var table = $('#excel tr').map(function() {
        return $(this).find('td').map(function() {
            return $(this).html();
        }).get();
    }).get();

    return table;
};

thank you

Upvotes: 1

Views: 1483

Answers (1)

MinusFour
MinusFour

Reputation: 14423

You could do it like this:

$.fn.toJson = function(){
  
  if(!this.is('table')){
    return;
    }
  
  var results = [],
      headings = [];
  
  this.find('thead tr th').each(function(index, value){
    headings.push($(value).text());
    });
  

  this.find('tbody tr').each(function(indx, obj){
    var row = { };
    var tds = $(obj).children('td');
    headings.forEach(function(key, index){
      var value = tds.eq(index).text();
      row[key] = value;
      });
    results.push(row);
    });
  
  return results;
  }

$(function(){
  $('#results').html(JSON.stringify($('#excel').toJson(), null, '\t'));
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="results"></pre>
<table id="excel">
  <thead>
    <tr role="row">
      <th>name</th>
      <th>number</th>
      <th>address</th>
    </tr>
  </thead>
  <tbody>
    <tr role="row" class="odd">
      <td class="sorting_1">Haroldas</td>
      <td>444</td>
      <td>address</td>
    </tr>
    <tr role="row" class="even">
      <td class="sorting_1">ted</td>
      <td>333</td>
      <td>kkk</td>
    </tr>
    <tr role="row" class="odd">
      <td class="sorting_1">tom</td>
      <td>999</td>
      <td>rrr</td>
    </tr>
  </tbody>
</table>

To use:

  $('tableSelector').toJson();

It's up to you to add those keys besides the table data.

Upvotes: 2

Related Questions