create a json array from html table

后端 未结 5 2008
渐次进展
渐次进展 2020-12-30 17:30

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

5条回答
  •  萌比男神i
    2020-12-30 18:03

    Something like this, assuming the first row is always the header (could certainly be changed to make it more flexible):

    function getData(table, format) {
        var rows = table.tBodies[0].rows,
            header_row = rows[0],
            result = [],
            header = [],
            format = format || function(val){return val;},
            i, j, cell, row, row_data;
    
        // extract header
        for(i = 0, l = header_row.cells.length; i < l; i++) {
            cell = header_row.cells[i];
            header.push((cell.textContent || cell.innerText));
        }
    
        // extract values
        for(i = 1, l = rows.length; i < l; i++) {
            row = rows[i];
            row_data = {};
            for(j = 0, l = row.cells.length; j < l; j++) {
                cell = row.cells[j];
                row_data[header[j]] = format(i, j, cell.textContent || cell.innerText);
            }
            result.push(row_data);
        }
        return result;
    }
    

    Usage is:

    var chartData = getData(referenceToTable, function(rowIndex, colIndex, value) {
        return +value; // shortcut to format text to a number
    });
    

    By passing a format function, you can format the values of each cell into the right data type.

    DEMO

    It works under the assumption that there is only one tbody element. You have to adjust it to your needs.

提交回复
热议问题