Last active
November 14, 2022 03:29
-
-
Save DeBraid/8772484 to your computer and use it in GitHub Desktop.
Using Chrome DevTools to scrape HTML table and convert to JSON.
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
// **************************************************** | |
// 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); | |
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
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?