Skip to content

Instantly share code, notes, and snippets.

@hyperking
Created August 19, 2015 22:28
Show Gist options
  • Save hyperking/fd5c2dbd8cf0bc1f96c0 to your computer and use it in GitHub Desktop.
Save hyperking/fd5c2dbd8cf0bc1f96c0 to your computer and use it in GitHub Desktop.
convert table element to json object
<table>
<thead>
<tr>
<th>Name</th>
<th>Hobby</th>
<th>Favorite Music</th>
</tr>
</thead>
<tbody>
<tr class="tabledata">
<td>Fred</td>
<td>Roller Skating</td>
<td>Disco</td>
</tr>
<tr class="tabledata">
<td>Helen</td>
<td>Rock Climbing</td>
<td>Alternative</td>
</tr>
<tr class="tabledata">
<td>Glen</td>
<td>Traveling</td>
<td>Classical</td>
</tr>
</tbody>
</table>
<script>
/*
Covert table into json object
var topics = [{
"title": "Sample Discussion Topic",
"postedby": "Design Tester",
"dateposted": "8/17/2015 4:18:27 PM"
}, {
"title": "Hello World Topic",
"postedby": "Design Tester",
"dateposted": "8/17/2015 4:18:27 PM"
}];
*/
function tableToJson(rowclass) {
//Clone pagination
$('.BBPPager').first().clone().appendTo('.content');
var rows = $('tr'+rowclass);
var rowdata = [];
//row data structure is based on the table columns.
//you will need to define the key value pairs for each object
rows.each(function (key, val) {
data_tds = $(val).find("td");
rowdata.push({
"title": $(data_tds[0]).text(),
"link":$.trim($(data_tds[0]).html()),
"city":$(data_tds[2]).text(),
"graduated":$(data_tds[1]).text(),
"state":$(data_tds[3]).text(),
"orgname":$(data_tds[6]).text()
});
});
return rowdata;
}
//execute script
tableToJson('.tabledata');
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment