Sei fortunato: non riuscivo a prendere sonno…
codice:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Esempio</title>
<script type="text/javascript">
var tableToJSON = (function () {
function getCells (oParent, aCells, sCellType) {
if (oParent.hasChildNodes()) {
for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
if (oNode.nodeName.toUpperCase() === "TABLE") { continue; }
getCells(oNode, aCells, sCellType);
}
}
oParent.nodeName.toUpperCase() === sCellType && aCells.push(oParent.textContent);
}
return function (oTable) {
var nCols, aRaw = [], aRows = [];
getCells(oTable, aRaw, "TH");
nCols = aRaw.length;
getCells(oTable, aRaw, "TD");
for (var oRow, nIdx, nLen = aRaw.length, nItem = nCols; nItem < nLen; nItem++) {
oRow = {};
for (nIdx = 0; nIdx < nCols; oRow[aRaw[nIdx++]] = aRaw[nItem]);
aRows.push(oRow);
}
return aRows;
}
})();
onload = function () {
var miaTabella = tableToJSON(document.getElementById("tabella"));
alert(JSON.stringify(miaTabella));
};
</script>
<style type="text/css">
</style>
</head>
<body>
<table id="tabella">
<thead>
<tr><th>Numero</th><th>E-Mail</th><th>Dati</th></tr>
</thead>
<tbody>
<tr>
<td>numero1</td>
<td>mail@da.estrarre1</td>
<td>data1</td>
</tr>
<tr>
<td>numero2</td>
<td>mail@da.estrarre2</td>
<td>data2</td>
</tr>
<tr>
<td>numero3</td>
<td>mail@da.estrarre3</td>
<td>data3</td>
</tr>
</tbody>
</table>
</body>
</html>
Ti comparirà un alert nel seguente formato…
codice:
[{
"Numero": "numero1",
"E-Mail": "numero1",
"Dati": "numero1"
}, {
"Numero": "mail@da.estrarre1",
"E-Mail": "mail@da.estrarre1",
"Dati": "mail@da.estrarre1"
}, {
"Numero": "data1",
"E-Mail": "data1",
"Dati": "data1"
}, {
"Numero": "numero2",
"E-Mail": "numero2",
"Dati": "numero2"
}, {
"Numero": "mail@da.estrarre2",
"E-Mail": "mail@da.estrarre2",
"Dati": "mail@da.estrarre2"
}, {
"Numero": "data2",
"E-Mail": "data2",
"Dati": "data2"
}, {
"Numero": "numero3",
"E-Mail": "numero3",
"Dati": "numero3"
}, {
"Numero": "mail@da.estrarre3",
"E-Mail": "mail@da.estrarre3",
"Dati": "mail@da.estrarre3"
}, {
"Numero": "data3",
"E-Mail": "data3",
"Dati": "data3"
}]