Jimmy
Jimmy

Reputation: 9815

Convert a HTML table data into a JSON object in jQuery

Anyone know how to convert an HTML table of values into a nice JSON object to be manipulated with jQuery?

Upvotes: 24

Views: 98329

Answers (3)

lightswitch05
lightswitch05

Reputation: 9428

I needed the same thing except with the ability to ignore columns, override values, and not be confused by nested tables. I ended up writing a jQuery plugin table-to-json:

https://github.com/lightswitch05/table-to-json

All you have to do is select your table using jQuery and call the plugin:

var table = $('#example-table').tableToJSON();

Here is a demo of it in action:

$('#run').click(function() {
  var table = $('#example-table').tableToJSON();
  console.log('Table:', table);
  alert(JSON.stringify(table, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/jquery.tabletojson.min.js"></script>

<table id='example-table'>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th data-override="Score">Points</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Jill</td>
      <td>Smith</td>
      <td data-override="disqualified">50</td>
    </tr>
    <tr>
      <td>Eve</td>
      <td>Jackson</td>
      <td>94</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>80</td>
    </tr>
    <tr>
      <td>Adam</td>
      <td>Johnson</td>
      <td>67</td>
    </tr>
  </tbody>
</table>

<button id="run">Convert!</button>

Upvotes: 20

Pointy
Pointy

Reputation: 413976

An HTML table? Like, all the <td> contents in a 2-d array?

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

Then just use $.json (or whatever library you want) to turn that into a JSON string.

edit — re-written to use the native (shim here) .map() from the array prototype:

var tbl = $('table#whatever tr').get().map(function(row) {
  return $(row).find('td').get().map(function(cell) {
    return $(cell).html();
  });
});

The jQuery .map() function has the "feature" of flattening returned arrays into the result array. That is, if the callback function returns a value that is itself an array, then instead of that returned array becoming the value of one cell of the .map() result, its elements are each added to the result.

It might work to use the original jQuery version and just wrap an extra array around the returned values.

Upvotes: 37

John Rumpel
John Rumpel

Reputation: 4615

Do you mean the following situation?

Given:

A1 B1 C1 ...
A2 B2 C2 ...
...

Needed:

{"1": ["A1", "B1", "C1", ...], 
 "2": ["A2", "B2", "C2", ...], ...}

So use the following function which creates a valid JSON-String function without trailing ",":

function html2json() {
   var json = '{';
   var otArr = [];
   var tbl2 = $('#dest_table tr').each(function(i) {        
      x = $(this).children();
      var itArr = [];
      x.each(function() {
         itArr.push('"' + $(this).text() + '"');
      });
      otArr.push('"' + i + '": [' + itArr.join(',') + ']');
   })
   json += otArr.join(",") + '}'

   return json;
}

Upvotes: 24

Related Questions