Parsing JSON objects and generating an HTML table dynamically with JavaScript involves iterating over the JSON data and constructing table rows and cells accordingly.
For example write the following:
Suppose you have a JSON object like this:
var jsonData = [
{ "name": "John", "age": 30, "city": "New York" },
{ "name": "Alice", "age": 25, "city": "Los Angeles" },
{ "name": "Bob", "age": 35, "city": "Chicago" }
];
You can generate an HTML table from this JSON data like this:
// Function to generate HTML table from JSON data
function generateTable(jsonData) {
var table = document.createElement('table');
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var headRow = document.createElement('tr');
// Add table header
Object.keys(jsonData[0]).forEach(function(key) {
var th = document.createElement('th');
th.textContent = key;
headRow.appendChild(th);
});
thead.appendChild(headRow);
table.appendChild(thead);
// Add table rows and cells
jsonData.forEach(function(rowData) {
var row = document.createElement('tr');
Object.values(rowData).forEach(function(value) {
var cell = document.createElement('td');
cell.textContent = value;
row.appendChild(cell);
});
tbody.appendChild(row);
});
table.appendChild(tbody);
return table;
}
// Get the container element where you want to append the table
var container = document.getElementById('table-container');
// Generate the table and append it to the container
container.appendChild(generateTable(jsonData));
In this code, the generateTable()
function takes the JSON data as input and creates an HTML table.
It first creates the <table>
, <thead>
, and <tbody>
elements.
Then, it creates the table header (<th>
) by iterating over the keys of the first object in the JSON data.
Next, it iterates over each object in the JSON array, creates a new table row (<tr>
), and populates it with table cells (<td>
) containing the values from the JSON object.
Finally, it appends the table to a container element in the HTML document.
Make sure to replace jsonData
with your actual JSON data and table-container
with the ID of the container where you want to append the table.