How To Convert JSON To HTML Table Using JavaScript Function


Converting JSON data to an HTML table. Using JavaScript functions, you can dynamically convert and display JSON objects in a structured HTML table format. Whether you're a beginner or an experienced developer, you'll find practical tips and code snippets to help you efficiently convert JSON data into a readable, user-friendly HTML table.

The webpage provides a detailed guide for converting JSON data to an HTML table using JavaScript. It includes code snippets for converting JSON to HTML tables and HTML tables back to JSON.

Online JSON to HTML Table Converter

Paste your JSON code here and easily convert it into an HTML table with just one click.

Note: The data you input into the text box is handled locally and offline in your web browser. We do not collect any information.

Add JavaScript array of object without declaring it as a variable. var arrya_name = [] anonymous array object [{"..."}, {"..."}, {"..."}]

Online HTML Table To JSON Converter

Paste your HTML table code here and easily convert it into an JSON with just one click.

JSON to HTML Table Converter Function

Here is a JavaScript function that converts a JSON object into an HTML table

This function returns an HTML table as a string

JavaScript
const jsonToHtmlTable = (json) => {
    // Check if json is an array and not empty
    if (!Array.isArray(json) || json.length === 0 || typeof json[0] !== "object") {
        return "";
    }
    // Function to escape HTML characters
    const escapeHtml = (string) => {
        return String(string).replace(/[&<>"]/g, (s) => {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
            } [s];
        });
    };
    // Extract keys (columns) from the JSON object
    const keys = Object.keys(json[0]);
    // Create table element
    let table = '<table class="my-table">';
    // Create table header
    table += "<thead><tr>";
    keys.forEach(key => {
        table += '<th>' + escapeHtml(key) + '</th>';
    });
    table += '</tr></thead>';
    // Create table body
    table += '<tbody>';
    json.forEach(row => {
        table += '<tr>';
        keys.forEach(key => {
            const value = row[key] !== null && row[key] !== undefined ? row[key] : "";
            table += '<td>' + escapeHtml(value) + '</td>';
        });
        table += "</tr>";
    });
    table += '</tbody>';
    // Close table element
    table += '</table>';
    return table;
};

Usage JSON to Table

HTML
<div id="preview-table"></div>
JavaScript
// Example usage:
// sample JSON data
const users = [
  { "name": "John", "age": 30, "city": "India" },
  { "name": "Anna", "age": 22, "city": "Japan" },
  { "name": "Mike", "age": 32, "city": "Philippines" }
];

const table = jsonToHtmlTable(users);
document.getElementById("preview-table").innerHTML = table;

Preview live

Click the button try it yourself edit and preview live

Try it your self

Table to JSON converter Function

Here is a JavaScript function that converts an HTML table into a JSON object

The function takes the ID of the table element. and returns the JSON array representing the table data

JavaScript
const htmlTableToJson = (table_id) => {
    // Find the table by its ID
    const table = document.getElementById(table_id);
    if (!table) {
        console.error('Table not found');
        return [];
    }
    // Initialize an array to store the JSON data
    const json = [];
    // Get the table headers
    const headers = [];
    const header_cells = table.querySelectorAll("thead th");
    if (header_cells.length === 0) {
        console.error('No table headers found');
        return [];
    }
    header_cells.forEach(cell => {
        headers.push(cell.innerText.trim());
    });
    // Get the table rows
    const rows = table.querySelectorAll("tbody tr");
    if (rows.length === 0) {
        console.error('No table rows found');
        return [];
    }
    // Iterate over each table row
    rows.forEach(row => {
        const row_data = {};
        const cells = row.querySelectorAll("td");
        cells.forEach((cell, index) => {
            row_data[headers[index]] = cell.innerText.trim();
        });
        json.push(row_data);
    });
    return json;
};

Usage Table to JSON

To use this function, make sure you have an HTML table with the specified id.

Here is a sample HTML table

This textarea is included to preview the JSON code.

HTML
<textarea style="width:100%;height:200px;" id="preview-json"></textarea>

<table class="my-table" id="json-table">
    <thead>
        <tr>
            <th>name</th>
            <th>age</th>
            <th>city</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John</td>
            <td>30</td>
            <td>India</td>
        </tr>
        <tr>
            <td>Anna</td>
            <td>22</td>
            <td>Japan</td>
        </tr>
        <tr>
            <td>Mike</td>
            <td>32</td>
            <td>Philippines</td>
        </tr>
    </tbody>
</table>
JavaScript
const json_data = htmlTableToJson('json-table');
const pretty_json = JSON.stringify(json_data, null, 4);
document.getElementById("preview-json").value = pretty_json

Preview Edit Code

Try it yourself edit and preview live

Try it your self