Convert an HTML table to JSON and export it to a file in JS

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
5 min

banner

# Table of Contents

  1. How to convert an HTML table to JSON
  2. How to convert an HTML table to an Array of Objects
  3. Convert an HTML table to JSON and export it as a JSON file

The article covers:

  1. How to convert an HTML table to a JSON array of arrays.
  2. How to convert an HTML table to a JSON array of objects.
  3. How to export the resulting JSON string to a .json file.

# How to convert an HTML table to JSON

To convert an HTML table to JSON:

  1. Store the values of the th elements in an array.
  2. Store the values of the td elements in an array.
  3. Concatenate the two arrays and use the JSON.stringify() method.

Here is the HTML for the example.

index.html
<!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>

example table

The code for this article is available on GitHub

Here is the code for the index.js file.

index.js
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 code for this article is available on GitHub

The toObject() function converts the table to an object that has 3 properties:

  1. table - an array containing the rows of the table.
index.js
// ๐Ÿ‘‡๏ธ [['Col 1','Col 2','Col 3'],['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] console.log(obj.table);
  1. thead - an array containing the header columns.
index.js
// ๐Ÿ‘‡๏ธ ['Col 1', 'Col 2', 'Col 3'] console.log(obj.thead);
  1. tbody - an array of arrays containing the rows from the body of the table.
index.js
// [['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.

index.js
const jsonStr = JSON.stringify(obj.table); // [["Col 1","Col 2","Col 3"],["A1","A2","A3"],["B1","B2","B3"],["C1","C2","C3"]] console.log(jsonStr);

# How to convert an HTML table to an Array of Objects

If you need to convert the HTML table to an array of objects:

  1. Get an array of the table's headings.
  2. Get an array of the table's rows.
  3. Iterate over the table's rows and store each heading as a key and the current th text content as the value.

The HTML for the example is the same as in the previous subheading.

index.html
<!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>
The code for this article is available on GitHub

Here is the related JavaScript code.

index.js
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 code for this article is available on GitHub

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.

# Convert an HTML table to JSON and export it as a JSON file

The following example:

  1. Converts the HTML table to a JSON array of objects (could be any other data structure).
  2. Exports the JSON to a file.

Here is the HTML for the example.

index.html
<!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>

html table with download as json button

The code for this article is available on GitHub

Here is the code for the index.js file.

index.js
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'); });

export json table to file

The code for this article is available on GitHub

Here are the contents of the exported .json file.

contents of 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.

index.js
const jsonStr = JSON.stringify( toArrayOfObjects(table), null, 2, );

export json table pretty print

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev