Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a json array from html table

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).

like image 581
Ali1S232 Avatar asked Dec 22 '22 14:12

Ali1S232


1 Answers

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 →

like image 171
mVChr Avatar answered Jan 07 '23 02:01

mVChr