Jimmy Jimmy - 9 months ago 85
jQuery Question

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?


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();

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.