Created
April 1, 2021 13:11
-
-
Save Vlasterx/61d6d1d833999743cdd5acc48f1f3b3b to your computer and use it in GitHub Desktop.
HTML table to JSON
This file contains hidden or 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
/** | |
* 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