Skip to content

Instantly share code, notes, and snippets.

@DeBraid
Last active November 14, 2022 03:29
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save DeBraid/8772484 to your computer and use it in GitHub Desktop.
Save DeBraid/8772484 to your computer and use it in GitHub Desktop.
Using Chrome DevTools to scrape HTML table and convert to JSON.
// ****************************************************
// USING JQUERY TO CONVERT HTML TABLE INTO JSON
// by Derek from www.cacheflow.ca
// Watch the video: http://youtu.be/DPOOIOU0zVA
// ****************************************************
// Step 1: Create keys for JSON object
var cols = $("#tableID thead tr th").map(function(){
return $(this).text();
});
// eliminate the extraneous strings from cols
var headers = cols.splice(10, cols.length);
// Fetch the data from the table body
var tableObject = $("#tableID tbody tr.tableClass").map(function(i){
var row = {};
$(this).find('td').each(function(i){
var rowName = headers[i];
row[rowName] = $(this).text();
});
return row;
}).get();
// convert object to JSON
JSON.stringify(tableObject);
@aeroxy
Copy link

aeroxy commented Mar 27, 2015

Excellent work Derek! If I use ajax call the get the DOM tree from a webpage, and then converting one of the table on the page, there will be a challenge since $('#ID') and $('.CLASS') will not be effective as query selectors. What would be your take on this challenge?

@darrylhebbes
Copy link

Excellent work Derek! If I use ajax call the get the DOM tree from a webpage, and then converting one of the table on the page, there will be a challenge since $('#ID') and $('.CLASS') will not be effective as query selectors. What would be your take on this challenge?

The DOM is a tree of nodes, just iterate over them

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