i have C++ program exporting log files as HTML table and I wanted to know if there is any way that i can parse that table(something like this):
<table>
<tr><td>id</td><td>value1</td><td>value2</td></tr>
<tr><td>0 </td><td>0 </td><td>0 </td></tr>
<tr><td>0 </td><td>1.5 </td><td>2.15 </td></tr>
</table>
into a JSON array (something like this) using a Javascript function:
var chartData = [
{id:"0",value1:"0",value2:"0"},
{id:"1",value1:"1.5",value2:"2.15"}];
The problem is that I want this function to work for every table given to it, with any possible row or column count(first row is always a header).
Here's my implementation:
var tableToObj = function( table ) {
var trs = table.rows,
trl = trs.length,
i = 0,
j = 0,
keys = [],
obj, ret = [];
for (; i < trl; i++) {
if (i == 0) {
for (; j < trs[i].children.length; j++) {
keys.push(trs[i].children[j].innerHTML);
}
} else {
obj = {};
for (j = 0; j < trs[i].children.length; j++) {
obj[keys[j]] = trs[i].children[j].innerHTML;
}
ret.push(obj);
}
}
return ret;
};
Which you would invoke like:
var obj = tableToObj( document.getElementsByTagName('table')[0] ); // or
var obj = tableToObj( document.getElementById('myTable') );
See working example →
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With