Skip to content

Instantly share code, notes, and snippets.

@rudyhuynh
Forked from johannesjo/table-to-json.js
Created April 15, 2021 09:06
Show Gist options
  • Save rudyhuynh/0ea45f712aa35d1e3301b6cd4fd0188a to your computer and use it in GitHub Desktop.
Save rudyhuynh/0ea45f712aa35d1e3301b6cd4fd0188a to your computer and use it in GitHub Desktop.
Snippet to convert html table to json (to be used with google chrome or similiar)
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=1; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
JSON.stringify(tableToJson($0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment