3

I came across a case where I have to convert an HTML table data into JSON. In this process I have to iterate through the table and convert one by one (row) into an array and then convert the whole array into JSON. How do I iterate through the table (each row and column)?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user227790
  • 41
  • 1
  • 1
  • 3
  • possible duplicate of [convert table into a JSON object in jQuery](http://stackoverflow.com/questions/2240005/convert-table-into-a-json-object-in-jquery) – dkretz Jun 05 '10 at 22:11

3 Answers3

8

First as fredrik pointed out we need to include https://github.com/douglascrockford/JSON-js.

Second we can use jQuery.fn.map and jQuery.fn.get to create an array of arrays (the tr:s) which contains the jQuery.fn.text content of the td elements:

var AoA = $('table tr').map(function(){
    return [
        $('td',this).map(function(){
            return $(this).text();
        }).get()
    ];
}).get();
var json = JSON.stringify(AoA);
ChrisF
  • 134,786
  • 31
  • 255
  • 325
azatoth
  • 2,379
  • 15
  • 18
4

Something like this? Fetching the content of each td into a myTable[rowIx][tableIx] array.

var myTable = [];
$('#myTable tr').each(function (i, tr) {
    var myTr = [];

    $('td', tr).each(function(j, td) {
        myTr.push($(td).html());
    });

    myTable.push(myTr);
});
nikib3ro
  • 20,366
  • 24
  • 120
  • 181
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
4

You also need to convert the JavaScript array (also work on objects, strings, etc.) into a JSON serialized string.

Add this to your page (will be added to jQuery soon):

<script type="text/javascript" src="http://json.org/json2.js"></script>

And then serialize your array:

JSON.stringify(myTable)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fredrik
  • 17,537
  • 9
  • 51
  • 71