Nate
Nate

Reputation: 2084

HTML Table to JSON

I need to take table rows and convert to JSON.

Any ideas? I have this code here but it does not work.

function tableToJSON(tableID) {
    return $(tableID + "  tr").map(function (row) {
        return row.descendants().pluck("innerHTML");
    }).toJSON();
}

Upvotes: 21

Views: 57855

Answers (8)

user1248475
user1248475

Reputation:

(function($) {

  $.extend($.fn, {

    tableRowsToJSONWithFilter: function(filter) {
      var tableSelector = this,
        item, attr, data, _JSON = [];
      if (typeof(tableSelector) !== 'object') {
        return new Error('Invalid tableSelect!');
      };
      $(tableSelector, 'tr').each(function(index, tr) {
        item = {};
        $('td', $(this)).each(function(index, td) {
          attr = $(td).attr('data-id');
          data = $(td).text();
          if (attr !== undefined && data !== '' && filter && new RegExp(filter, 'i').test(attr)) {
            item[attr] = data;
          };
        });
        _JSON.push(item);
      });
      return _JSON;
    }

  })

})(jQuery);

console.log(
  $('#answered').tableRowsToJSONWithFilter('yodawg')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="answered">
  <tbody>
    <tr>
      <td data-id="user.email">[email protected]</td>
      <td data-id="meme.yodawg">Yo Dog! I Heard you liked answers, so I answered your question, with a method wrapped in a jQuery plugin!</td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Kevin Potgieter
Kevin Potgieter

Reputation: 798

Here is one which parses merged rows successfully.

-- Merged rows example:

enter image description here

-- parse

function tableToJson (table) {
        let data = [];

        // first row needs to be headers
        let headers = [];
        for (let i = 0; i < table.rows[0].cells.length; i++) {
            headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase()
            headers[i] = headers[i]
                .replace(new RegExp('<b>', 'gi'), '')
                .replace(new RegExp('</b>', 'gi'), '')
                .replace(new RegExp('\r?\n', 'gi'), '')
                .trim();
        }

        // go through cells
        for (let i = 1; i < table.rows.length; i++) {

            let tableRow = table.rows[i];
            let rowData = {};
            let rowSpanValue = ''
            if (table.rows[i - 1] && table.rows[i - 1].cells[0].getAttribute("rowspan"))
                rowSpanValue = table.rows[i - 1].cells[0].innerText

            if (!!rowSpanValue)
                rowData[headers[0]] = rowData[headers[0]] || rowSpanValue

            for (let j = 0; j < tableRow.cells.length; j++) {

                let header = !!rowSpanValue ? headers[j + 1] : headers[j]
                let data = tableRow.cells[j]
                let result;
                if (data.querySelector('a')) {
                    result = tableRow.cells[j].querySelector('a').innerText;
                } else {
                    result = tableRow.cells[j].innerText;
                }
                rowData[header] = (rowData[header] || result).replace(new RegExp('\r?\n', 'gi'), '').trim();
            }

            data.push(rowData);
        }

        return data;
    }

Upvotes: 0

Flavio Ariano
Flavio Ariano

Reputation: 71

HTML table with thead and tbody:

    function htmlTableToJson(table, edit = 0, del = 0) {
        // If exists the cols: "edit" and "del" to remove from JSON just pass values = 1 to edit and del params
        var minus = edit + del;
        var data = [];
        var colsLength = $(table.find('thead tr')[0]).find('th').length - minus;
        var rowsLength = $(table.find('tbody tr')).length;

        // first row needs to be headers
        var headers = [];
        for (var i=0; i<colsLength; i++) {
            headers[i] = $(table.find('thead tr')[0]).find('th').eq(i).text();
        }

        // go through cells
        for (var i=0; i<rowsLength; i++) {
            var tableRow = $(table.find('tbody tr')[i]);
            var rowData = {};
            for (var j=0; j<colsLength; j++) {
                rowData[ headers[j] ] = tableRow.find('td').eq(j).text();
            }
            data.push(rowData);
        }       
        return data;
    }

Upvotes: 3

Dana Spitzer Friedlander
Dana Spitzer Friedlander

Reputation: 1408

This one worked for me: (I had only 2 lines in my table, th and td)

function htmlToJson(table) {
    var obj = {},
        itemsLength = $(table.find('tbody tr')[0]).find('th').length;
    for (i=0;i<itemsLength;i++) {
        key = $(table.find('tbody tr')[0]).find('th').eq(i).text();
        value = $(table.find('tbody tr')[1]).find('td').eq(i).text();
        obj[key] = value;
    }
    return JSON.stringify(obj)
}

Upvotes: 3

slandau
slandau

Reputation: 24052

function tableToJson(table) {
    var data = [];

    // first row needs to be headers
    var headers = [];
    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }

    // go through cells
    for (var i=1; i<table.rows.length; i++) {

        var tableRow = table.rows[i];
        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {

            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

        }

        data.push(rowData);
    }       

    return data;
}

Taken from John Dyer's Blog

Upvotes: 26

lightswitch05
lightswitch05

Reputation: 9428

I was unhappy with all the solutions above and ended up writing my own jQuery plugin to accomplish this. It is very similar to the solution but accepts several options to customize the results, such as ignoring hidden rows, overriding column names, and overriding cell values

The plugin can be found here along with some examples if this is more what your looking for: https://github.com/lightswitch05/table-to-json

Upvotes: 5

Dave Ward
Dave Ward

Reputation: 60580

You should find this helpful: http://encosia.com/use-jquery-to-extract-data-from-html-lists-and-tables/

Upvotes: 3

Saul Berardo
Saul Berardo

Reputation: 2600

try $("#"+tableID + " tr") instead.

Upvotes: 3

Related Questions