Table to JSON
by amitrdx
HTML
<table id="students" border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr class="student">
<td>Oscar</td>
<td>23</td>
<td>16.5</td>
</tr>
<tr class="student">
<td>Antonio</td>
<td>32</td>
<td>14</td>
</tr>
<tr class="student">
<td>Jessica</td>
<td>21</td>
<td>19</td>
</tr>
</tbody>
</table>
CSS
table {
-moz-border-radius: 5px !important;
-webkit-border-radius: 5px !important;
border-collapse: separate !important;
border: 1px solid #cccccc !important;
}
table th, table td { border: 1px solid #cccccc !important }
table th:first-child {
-moz-border-radius: 5px 0 0 0 !important;
-webkit-border-radius: 5px 0 0 0 !important;
}
table th:last-child {
-moz-border-radius: 0 5px 0 0 !important;
-webkit-border-radius: 0 5px 0 0 !important;
}
table tr:last-child td:first-child {
-moz-border-radius: 0 0 0 5px !important;
-webkit-border-radius: 0 0 0 5px !important;
}
table tr:last-child td:last-child {
-moz-border-radius: 0 0 5px 0 !important;
-webkit-border-radius: 0 0 5px 0 !important;
}
table tr:hover td { background-color: #ddd !important }
JavaScript
var tbl = $('table#students tr').map(function() {
return $(this).find('td').map(function() {
return $(this).text();
}).get();
}).get();
var tbl2 = $('#students tr:has(td)').map(function(i, v) {
var $td = $('td', this);
return {
id: ++i,
name: $td.eq(0).text(),
age: $td.eq(1).text(),
grade: $td.eq(2).text()
}
}).get();
console.log(tbl);
console.log(tbl2);
console.log(JSON.stringify(tbl2))