Home >Web Front-end >JS Tutorial >How Can I Generate an HTML Table from JSON Data Using JavaScript?

How Can I Generate an HTML Table from JSON Data Using JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-02 21:00:16402browse

How Can I Generate an HTML Table from JSON Data Using JavaScript?

Convert JSON Data to HTML Table

Question:

Is there a way to dynamically generate an HTML table from JSON data using jQuery or JavaScript?

Answer:

Yes, there are several libraries that can help you achieve this. One common option is to use the jQuery DataTables plugin. However, if you prefer not to use any libraries, you can also create your own table using pure JavaScript.

JavaScript Code:

Here is a JavaScript code snippet to build an HTML table from JSON data:

// JSON data
var myList = [
  { "name": "abc", "age": 50 },
  { "age": "25", "hobby": "swimming" },
  { "name": "xyz", "hobby": "programming" }
];

// Build the table
var table = document.createElement('table');
var headerRow = document.createElement('tr');

// Add header row with column names
for (var key in myList[0]) {
  var th = document.createElement('th');
  th.textContent = key;
  headerRow.appendChild(th);
}
table.appendChild(headerRow);

// Add data rows
for (var i = 0; i < myList.length; i++) {
  var row = document.createElement('tr');
  for (var key in myList[i]) {
    var td = document.createElement('td');
    td.textContent = myList[i][key];
    row.appendChild(td);
  }
  table.appendChild(row);
}

// Append the table to the DOM
document.body.appendChild(table);

This code assumes that all objects in the JSON list have the same set of keys. If this is not the case, you may need to add additional logic to handle missing keys.

The above is the detailed content of How Can I Generate an HTML Table from JSON Data Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn