Skip to content

Instantly share code, notes, and snippets.

@poteto
Last active May 9, 2024 23:48
Show Gist options
  • Save poteto/9dc36a3e856ba0ce010d to your computer and use it in GitHub Desktop.
Save poteto/9dc36a3e856ba0ce010d to your computer and use it in GitHub Desktop.
Converts a HTML table with `thead` and `tbody` into an array of objects. You can then use JSON.stringify(json) or copy(json) to your clipboard.
javascript:void%20function(){(function(t){t.extend(t.fn,{tableToJSON:function(){var%20n=this,r=t(%22thead%20th%22,n).map(function(n,r){return%20t(r).text().trim().toLowerCase()});return%20t(%22tbody%20tr%22,n).map(function(n,e){var%20o=t(e),a={};return%20t(%22td%22,o).each(function(n,e){var%20o=r[n];a[o]=t(e).text().trim()}),a}).toArray()}})})(jQuery)}();
// Usage: var json = $('table').tableToJSON();
// JSON.stringify(json);
// copy(json);
(function($) {
$.extend($.fn, {
tableToJSON: function() {
var $el = this;
var attrs = $('thead th', $el).map(function(idx, heading) {
return $(heading).text().trim().toLowerCase();
});
return $('tbody tr', $el).map(function(idx, row) {
var $row = $(row);
var obj = {};
$('td', $row).each(function(idx, col) {
var attr = attrs[idx];
obj[attr] = $(col).text().trim();
});
return obj;
}).toArray();
}
});
})(jQuery);
@StefanoF
Copy link

good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment