Last updated: Mar 7, 2024
Reading timeยท5 min
The article covers:
.json
file.To convert an HTML table to JSON:
th
elements in an array.td
elements in an array.JSON.stringify()
method.Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">bobbyhadz.com</div> <br /> <br /> <br /> <table id="my-table"> <thead> <tr> <th>Col 1</th> <th>Col 2</th> <th>Col 3</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>A2</td> <td>A3</td> </tr> <tr> <td>B1</td> <td>B2</td> <td>B3</td> </tr> <tr> <td>C1</td> <td>C2</td> <td>C3</td> </tr> </tbody> </table> <script src="index.js"></script> </body> </html>
Here is the code for the index.js
file.
function toObject(table) { const thead = Array.from(table.tHead.rows[0].children).map( el => el.textContent, ); const tbody = Array.from(table.tBodies[0].rows).map(row => Array.from(row.cells).map(cell => cell.textContent), ); return { table: [thead].concat(tbody), thead, tbody, }; } const table = document.getElementById('my-table'); const obj = toObject(table); // ๐๏ธ [['Col 1','Col 2','Col 3'],['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] console.log(obj.table); // ๐๏ธ ['Col 1', 'Col 2', 'Col 3'] console.log(obj.thead); // [['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] console.log(obj.tbody); const jsonStr = JSON.stringify(obj.table); // [["Col 1","Col 2","Col 3"],["A1","A2","A3"],["B1","B2","B3"],["C1","C2","C3"]] console.log(jsonStr);
The toObject()
function converts the table to an object that has 3 properties:
table
- an array containing the rows of the table.// ๐๏ธ [['Col 1','Col 2','Col 3'],['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] console.log(obj.table);
thead
- an array containing the header columns.// ๐๏ธ ['Col 1', 'Col 2', 'Col 3'] console.log(obj.thead);
tbody
- an array of arrays containing the rows from the body of the table.// [['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] console.log(obj.tbody);
If you need to convert any of the properties to JSON, use the JSON.stringify method.
const jsonStr = JSON.stringify(obj.table); // [["Col 1","Col 2","Col 3"],["A1","A2","A3"],["B1","B2","B3"],["C1","C2","C3"]] console.log(jsonStr);
If you need to convert the HTML table to an array of objects:
th
text content as the value.The HTML for the example is the same as in the previous subheading.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">bobbyhadz.com</div> <br /> <br /> <br /> <table id="my-table"> <thead> <tr> <th>Col 1</th> <th>Col 2</th> <th>Col 3</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>A2</td> <td>A3</td> </tr> <tr> <td>B1</td> <td>B2</td> <td>B3</td> </tr> <tr> <td>C1</td> <td>C2</td> <td>C3</td> </tr> </tbody> </table> <script src="index.js"></script> </body> </html>
Here is the related JavaScript code.
function toArrayOfObjects(table) { const columns = Array.from(table.querySelectorAll('th')).map( heading => heading.textContent, ); const rows = table.querySelectorAll('tbody > tr'); return Array.from(rows).map(row => { const dataCells = Array.from(row.querySelectorAll('td')); return columns.reduce((obj, column, index) => { obj[column] = dataCells[index].textContent; return obj; }, {}); }); } const table = document.getElementById('my-table'); // [ // { // "Col 1": "A1", // "Col 2": "A2", // "Col 3": "A3" // }, // { // "Col 1": "B1", // "Col 2": "B2", // "Col 3": "B3" // }, // { // "Col 1": "C1", // "Col 2": "C2", // "Col 3": "C3" // } // ] console.log(toArrayOfObjects(table)); const jsonStr = JSON.stringify(toArrayOfObjects(table)); // [{"Col 1":"A1","Col 2":"A2","Col 3":"A3"},{"Col 1":"B1","Col 2":"B2","Col 3":"B3"},{"Col 1":"C1","Col 2":"C2","Col 3":"C3"}] console.log(jsonStr);
The toArrayOfObjects()
function takes a table element as a parameter and
returns an array of objects.
The table headings are used as properties in each object and the text content of
the td
elements is used as the values.
If you need to convert the array of objects to a JSON string, use the
JSON.stringify()
method.
The following example:
Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">bobbyhadz.com</div> <br /> <br /> <br /> <table id="my-table"> <thead> <tr> <th>Col 1</th> <th>Col 2</th> <th>Col 3</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>A2</td> <td>A3</td> </tr> <tr> <td>B1</td> <td>B2</td> <td>B3</td> </tr> <tr> <td>C1</td> <td>C2</td> <td>C3</td> </tr> </tbody> </table> <button id="btn">Click to Download Table as JSON</button> <script src="index.js"></script> </body> </html>
Here is the code for the index.js
file.
function toArrayOfObjects(table) { const columns = Array.from(table.querySelectorAll('th')).map( heading => heading.textContent, ); const rows = table.querySelectorAll('tbody > tr'); return Array.from(rows).map(row => { const dataCells = Array.from(row.querySelectorAll('td')); return columns.reduce((obj, column, index) => { obj[column] = dataCells[index].textContent; return obj; }, {}); }); } const table = document.getElementById('my-table'); function downloadJSONTable(jsonStr, fileName) { const dataStr = `data:text/json;charset=utf-8,${encodeURIComponent( jsonStr, )}`; const anchorElement = document.createElement('a'); anchorElement.href = dataStr; anchorElement.download = `${fileName}.json`; document.body.appendChild(anchorElement); anchorElement.click(); document.body.removeChild(anchorElement); } const downloadButton = document.getElementById('btn'); downloadButton.addEventListener('click', () => { const jsonStr = JSON.stringify(toArrayOfObjects(table)); downloadJSONTable(jsonStr, 'myFile'); });
Here are the contents of the exported .json
file.
The downloadJSONTable
function takes a JSON string and the name the downloaded
file should have on the user's file system as parameters and then exports the
supplied JSON string to a file.
The file is a bit difficult to read because it only consists of a single line,
however, you could pretty print the JSON by passing a third argument to the
JSON.stringify()
method.
const jsonStr = JSON.stringify( toArrayOfObjects(table), null, 2, );
The third argument is the indentation of the JSON string.
The new JSON string is much more readable as each key-value pair is displayed on a separate line.
I've also written an article on How to fetch and display JSON data in HTML using JavaScript.
You can learn more about the related topics by checking out the following tutorials: