Skip to content

Instantly share code, notes, and snippets.

@son0fhobs
Last active April 7, 2016 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save son0fhobs/9460703 to your computer and use it in GitHub Desktop.
Save son0fhobs/9460703 to your computer and use it in GitHub Desktop.
HTML Table to json
// check for jQuery, load 1.9.1 if not there
// csv to json - other gist.
// html to json - this gist
// json to csv and download - https://gist.github.com/Sikwan/4326948
// json to table - ? - setup datatables php to js. filters and all? Booya.
// combine all these into a single object?
if(typeof jQuery !== 'function'){
var jqueryScript = document.createElement('script');
jqueryScript.type = 'text/javascript';
jqueryScript.src = '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';
var head = document.getElementsByTagName('script')[0]; head.appendChild(jqueryScript);
jqueryScript.onload = start_bookmarklet;
function start_bookmarklet(){
console.log('jquery loaded');
$.noConflict();
bookmarklet_code(jQuery);
}
}else{
bookmarklet_code(jQuery);
}
// table.table-bordered.table-striped - moz.
function bookmarklet_code($){
// actual bookmarklet - propt for table selector
var tableSelector = prompt('Table jQuery Selector','#metrics');
var $table = $(tableSelector); // or assign table element
console.log($table.find('thead').html());
// have option either keepFields or removeFields
var options = {
htmlCells: false,
keepFields:['urlmetric', 'description', 'responsefield']
};
jsonTable = convert_table_to_json($table, options);
console.log(JSON.stringify(jsonTable));
function convert_table_to_json($table, userOptions){
var options = {
htmlCells: false,
keepFields:[]
};
if(typeof options !== 'undefined'){
for (var name in options) { options[name] = userOptions[name]; }
}
var is_assoc = false; // if headers thus json, else just array
var headers = [];
var headerName = ''; // used temporarily for clarity
var tableData = [];
if($table.find('thead th').length){
is_assoc = true;
$table.find('thead th').each(function(){
headerName = $(this).text().replace(/\s+/gi, '_').replace(/[^a-zA-Z]*/gi, '').toLowerCase();
// console.log(headerName);
headers.push(headerName);
});
}
if($table.find('tbody tr').length){
$table.find('tbody tr').each(function(i){
// cycle through rows
// console.log(tableData);
// console.log(i);
tableData[i] = (is_assoc) ? {} : [];
$(this).find('td').each(function(d){
// cycle through cells
console.log(headers[d]);
if(is_assoc){
if( !options.keepFields || ~options.keepFields.indexOf(headers[d]) ){
tableData[i][headers[d]] = (options.htmlCells) ? $(this).html() : $(this).text();
}
// keep html within cells or not
}else{
tableData[i][d] = (options.htmlCells) ? $(this).html() : $(this).text();
}
// console.log($(this).text());
});
});
}
return tableData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment