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条回答
2020-12-30 17:52
I needed the same thing except with the ability to ignore columns, override values, and not be confused by nested tables. I ended up writing a jQuery plugin table-to-json
:
https://github.com/lightswitch05/table-to-json
All you have to do is select your table using jQuery and call the plugin:
var table = $('#example-table').tableToJSON();
Here is a demo of it in action using your data:
http://jsfiddle.net/dGPks/199/
2020-12-30 17:53
Since that table format looks like well-formed XML, I'd use XSLT to make the conversion; your C++ program could then just invoke an XSLT engine.
2020-12-30 18:02
You could do it using the jquery framework. I
<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
var chartData = [];
$("table tr").each(function(i){
if(i==0) return;
var id = $.trim($(this).find("td").eq(0).html());
var value1 = $.trim($(this).find("td").eq(1).html());
var value2 = $.trim($(this).find("td").eq(2).html());
chartData.push({id: id, value1: value1, value2: value2});
});
//now you have the chartData array filled
});
</script>
Cheers.
2020-12-30 18:03
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 →
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.