views:

1005

answers:

4

I came across a case where I have to convert html table data into json. In this process I have to iterate through table and convert one by one(row) into array and then convert the whole array into json? Need help in iterating through table(each ow and column)?

+1  A: 

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(i, td) {

        myTr.push($(td).html());

    }

    myTable.push(myTr);
});
David Hedlund
Thank you. Was looking for a similar thing myself
Checksum
+2  A: 

You also need to convert the JavaScript Array(also work on Objects,Strings etc) in to 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"&gt;&lt;/script&gt;

And then serialize your Array:

JSON.stringify(myTable)

..fredrik

fredrik
+1  A: 

I wrote a plugin for this, it has a few bells and whistles. Check it out at:

http://www.fletchzone.com/post/jQuery-Convert-HTML-Table-to-JSON.aspx

Fletch
+2  A: 

First as fredrik pointed out we need to include http://json.org/json2.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);
azatoth