JavaScript JSON HTML

Generating HTML from JSON data is a common task in web development. You can fetch JSON data from APIs and dynamically create HTML elements to display the information.

Note ? JSONPlaceholder is a fake Online REST API for Testing and Prototyping.

Example: Creating HTML Table from JSON

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>JSON to HTML Example</title>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
         margin: 20px;
      }
      .header {
         font-size: 18px;
         font-weight: 500;
         color: red;
         margin-bottom: 10px;
      }
      .employee-table {
         border-collapse: collapse;
         width: 100%;
         margin: 10px 0;
      }
      .employee-table th, .employee-table td {
         border: 1px solid #ccc;
         padding: 8px;
         text-align: left;
      }
      .employee-table th {
         background-color: #f2f2f2;
      }
      .btn {
         background-color: #4CAF50;
         color: white;
         padding: 10px 20px;
         border: none;
         cursor: pointer;
         margin: 10px 0;
      }
   </style>
</head>
<body>
   <h1>JSON to HTML Table</h1>
   <div class="header">EMPLOYEE DIRECTORY</div>
   
   <table class="employee-table">
      <thead>
         <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Website</th>
         </tr>
      </thead>
      <tbody id="employee-body">
      </tbody>
   </table>
   
   <button class="btn" onclick="loadEmployees()">Load Employee Data</button>
   <p>Click the button above to fetch and display employee data from JSON API</p>

   <script>
      function loadEmployees() {
         const tableBody = document.getElementById("employee-body");
         
         fetch("https://jsonplaceholder.typicode.com/users")
            .then(response => response.json())
            .then(users => {
               // Clear existing content
               tableBody.innerHTML = "";
               
               // Create table rows from JSON data
               users.forEach(user => {
                  const row = document.createElement("tr");
                  row.innerHTML = `
                     <td>${user.id}</td>
                     <td>${user.name}</td>
                     <td>${user.email}</td>
                     <td>${user.phone}</td>
                     <td>${user.website}</td>
                  `;
                  tableBody.appendChild(row);
               });
            })
            .catch(error => {
               console.error("Error fetching data:", error);
               tableBody.innerHTML = "<tr><td colspan='5'>Error loading data</td></tr>";
            });
      }
   </script>
</body>
</html>

How It Works

The example demonstrates several key concepts:

  • Fetch API: Retrieves JSON data from the JSONPlaceholder API
  • JSON Parsing: Converts the response to JavaScript objects
  • Dynamic HTML Creation: Uses template literals and DOM manipulation to create table rows
  • Error Handling: Catches and displays errors if the API request fails

Alternative Method: Using innerHTML

// Alternative approach using innerHTML to build the entire table
function loadEmployeesWithInnerHTML() {
   const container = document.getElementById("employee-container");
   
   fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(users => {
         let html = `
            <table class="employee-table">
               <tr><th>Name</th><th>Email</th><th>Phone</th></tr>
         `;
         
         users.forEach(user => {
            html += `
               <tr>
                  <td>${user.name}</td>
                  <td>${user.email}</td>
                  <td>${user.phone}</td>
               </tr>
            `;
         });
         
         html += `</table>`;
         container.innerHTML = html;
      });
}

Key Points

  • Always handle errors when fetching external data
  • Use template literals (backticks) for cleaner HTML string creation
  • Consider using createElement() for better performance with large datasets
  • Sanitize user data to prevent XSS attacks in production applications

Conclusion

Converting JSON data to HTML allows you to create dynamic web content. Use the Fetch API to retrieve data and DOM methods to generate HTML elements efficiently.

Updated on: 2026-03-15T23:18:59+05:30

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements