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)?
views:
1005answers:
4
+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
2009-12-09 08:58:43
Thank you. Was looking for a similar thing myself
Checksum
2010-03-30 01:21:42
+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"></script>
And then serialize your Array:
JSON.stringify(myTable)
..fredrik
fredrik
2009-12-09 09:55:17
+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
2010-06-05 21:49:38
+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
2010-06-05 22:05:16