Skip to content

Instantly share code, notes, and snippets.

@Vlasterx
Created April 1, 2021 13:11
Show Gist options
  • Save Vlasterx/61d6d1d833999743cdd5acc48f1f3b3b to your computer and use it in GitHub Desktop.
Save Vlasterx/61d6d1d833999743cdd5acc48f1f3b3b to your computer and use it in GitHub Desktop.
HTML table to JSON
/**
* Recursive function that parses table elements
*
* @param elHtml - HTML object that contains table
* @returns { Object } JSON element with parsed table
*/
const parseTable = (elHtml = null) => {
if (elHtml === null) { return false }
let elName = String(elHtml.nodeName).toLowerCase()
let elJson = { nodeName: elName }
if (['caption', 'td', 'th'].includes(elName)) {
elJson.content = elHtml.textContent.trim()
}
if ('colspan' in elHtml) { elJson.colspan = elHtml.colspan }
if ('rowspan' in elHtml) { elJson.rowspan = elHtml.rowspan }
if ('children' in elHtml && elHtml.children.length > 0) {
elJson.children = []
elHtml.children.forEach((childElHtml) => {
elJson.children.push(parseTable(childElHtml))
})
}
return elJson
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment