Last active
May 9, 2024 23:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)}(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good!