23

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

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Jimmy
  • 9,346
  • 13
  • 55
  • 77
  • 1
    What do you mean by "table"? Database table? HTML table? – Sampson Feb 10 '10 at 20:13
  • possible duplicate of [Iterate through html table using jQuery, converting the data in the table into JSON](http://stackoverflow.com/questions/1872485/iterate-through-html-table-using-jquery-converting-the-data-in-the-table-into-js) –  Jun 09 '10 at 01:03

3 Answers3

35

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.

Pointy
  • 371,531
  • 55
  • 528
  • 584
  • The joke here may be that this doesn't really work. The jQuery `.map()` method has the (quite questionable, if you ask me) feature of flattening returned arrays. This basic approach would work however with the native `.map()` that newer JavaScript environments provide via the Array prototype. – Pointy May 02 '13 at 18:25
  • It is very helpful!! BTW @Pointy, what if very TD has a single class in it, eg bah bah bah..., can I convert it to json, so class name became property name like that ==> "message" : "bah bah bah...", thanks a lot –  Aug 24 '17 at 06:34
  • @VirtualJasper yes you could certainly do that, but you'd need to construct an object for each cell. I'd ask a new question. – Pointy Aug 24 '17 at 12:49
23

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;
}
John Rumpel
  • 4,125
  • 4
  • 29
  • 43
18

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:

http://jsfiddle.net/Crw2C/173/

lightswitch05
  • 8,149
  • 6
  • 45
  • 71
  • The bad thing is, if there is a html tag within the cell, it will be replaced with empty string. – Jerry Liang Jul 22 '15 at 19:19
  • @JerryLiang there is an option `allowHTML` to preserve HTML tags – lightswitch05 Jul 22 '15 at 19:20
  • @lightswitch05 in your jsfiddle if table contains dropdown than how to get only selected value in json ...(In my case senario is same as you said also working fine your fiddle but in my table on more column for State(dropdown) than in json all data given for dropdown.plz help me...Thanks) – Ghanshyam Lakhani Jul 13 '17 at 10:36
  • Ghanshyam, don't use this tool to extract form data, use a standard form – lightswitch05 Jul 13 '17 at 14:35