How to Fetch Data from JSON file and Display it in an HTML Table using jQuery?

JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the standard for transmitting data between servers and web applications. With jQuery, you can easily fetch data from a JSON file and dynamically display it in an HTML table, creating interactive and data-driven web pages.

Syntax

The primary jQuery method for fetching JSON data is

$.getJSON(url, data, success)

Parameters

  • url The URL of the JSON file or API endpoint from which to retrieve data. Can be relative or absolute.

  • data (optional) Additional data to send with the request as an object or query string.

  • success A callback function that executes when the request succeeds, receiving the JSON data as a parameter.

For iterating through JSON data, jQuery provides

$.each(data, function(index, item) {
    // Process each item
});

Here, index represents the current position in the array, and item contains the current object being processed.

Creating the JSON Data File

First, create a JSON file named jsonexdata.json with sample data. This file should be placed in the same directory as your HTML file

[
  {
    "name": "Neehar Peter",
    "email": "peterk36@gmail.com",
    "phone": "693-857-4120",
    "investment": "$5,200"
  },
  {
    "name": "Youssef Ibrahim",
    "email": "youssef221@ymail.com",
    "phone": "384-726-9150",
    "investment": "$7,500"
  },
  {
    "name": "Rajesh Kumar",
    "email": "rajesh@outlook.com",
    "phone": "246-135-7908",
    "investment": "$3,250"
  },
  {
    "name": "Mukesh Ratan",
    "email": "ratanm.23@hotmail.com",
    "phone": "570-912-6384",
    "investment": "$10,300"
  }
]

Basic Example Fetching and Displaying JSON Data

Following example demonstrates how to fetch JSON data and display it in an HTML table

<!DOCTYPE html>
<html>
<head>
  <title>Display JSON Data in HTML Table</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    body { 
      font-family: Arial, sans-serif; 
      padding: 20px;
    }
    h1 { 
      text-align: center; 
      color: #333; 
    }
    table { 
      width: 100%; 
      border-collapse: collapse; 
      margin: 20px 0;
    }
    th, td { 
      padding: 12px 15px; 
      text-align: left; 
      border: 1px solid #ddd; 
    }
    th { 
      background-color: #4CAF50; 
      color: white; 
      font-weight: bold;
    }
    tr:nth-child(even) { 
      background-color: #f9f9f9; 
    }
    tr:hover { 
      background-color: #f5f5f5; 
    }
  </style>
</head>
<body>
  <h1>JSON Data to HTML Table</h1>
  <table id="data-table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
        <th>Investment</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
  <script>
    $(document).ready(function() {
      $.getJSON("jsonexdata.json", function(data) {
        var tableBody = $("#data-table tbody");
        
        $.each(data, function(index, person) {
          var row = $("<tr></tr>");
          
          row.append($("<td></td>").text(person.name));
          row.append($("<td></td>").text(person.email));
          row.append($("<td></td>").text(person.phone));
          row.append($("<td></td>").text(person.investment));
          
          tableBody.append(row);
        });
      }).fail(function() {
        alert("Error loading JSON data");
      });
    });
  </script>
</body>
</html>

The above code creates a table with investor data loaded from the JSON file. The table displays names, emails, phone numbers, and investment amounts in a clean, styled format.

Enhanced Example with Error Handling

Following example includes better error handling and loading indicators

<!DOCTYPE html>
<html>
<head>
  <title>JSON to HTML Table with Error Handling</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    body { 
      font-family: Arial, sans-serif; 
      padding: 20px; 
      background-color: #f4f4f4;
    }
    .container { 
      max-width: 800px; 
      margin: 0 auto; 
      background: white; 
      padding: 20px; 
      border-radius: 8px;
    }
    h1 { 
      text-align: center; 
      color: #2c3e50; 
      margin-bottom: 30px;
    }
    table { 
      width: 100%; 
      border-collapse: collapse; 
    }
    th, td { 
      padding: 12px; 
      text-align: left; 
      border-bottom: 1px solid #ddd; 
    }
    th { 
      background-color: #3498db; 
      color: white; 
    }
    .loading { 
      text-align: center; 
      color: #7f8c8d; 
      font-style: italic;
    }
    .error { 
      color: #e74c3c; 
      text-align: center; 
      font-weight: bold;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>Investment Portfolio</h1>
    <div id="status" class="loading">Loading data...</div>
    <table id="data-table" style="display: none;">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Phone</th>
          <th>Investment</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>
  <script>
    $(document).ready(function() {
      $.getJSON("jsonexdata.json")
        .done(function(data) {
          $("#status").hide();
          $("#data-table").show();
          
          var tableBody = $("#data-table tbody");
          
          $.each(data, function(index, person) {
            var row = "<tr>" +
                     "<td>" + person.name + "</td>" +
                     "<td>" + person.email + "</td>" +
                     "<td>" + person.phone + "</td>" +
                     "<td>" + person.investment + "</td>" +
                     "</tr>";
            tableBody.append(row);
          });
        })
        .fail(function() {
          $("#status").removeClass("loading").addClass("error")
                     .text("Error: Could not load JSON data. Please check if the file exists.");
        });
    });
  </script>
</body>
</html>

This enhanced version includes a loading message, error handling, and improved styling for better user experience.

How It Works

The process follows these key steps

  1. DOM Ready $(document).ready() ensures the code runs after the HTML is fully loaded.

  2. AJAX Request $.getJSON() sends an asynchronous HTTP request to fetch the JSON file.

  3. Data Processing Upon successful retrieval, the JSON data is parsed automatically by jQuery.

  4. Table Population $.each() iterates through each object in the JSON array, creating table rows and cells dynamically.

  5. DOM Manipulation Each row is appended to the table body using jQuery's append() method.

JSON to HTML Table Flow JSON File $.getJSON() $.each() HTML Table Fetch Parse Generate

Common Use Cases

This technique is commonly used for

  • Dynamic Data Display Loading product catalogs, user lists, or inventory data without page refreshes.

  • API Integration Fetching data from external APIs and presenting it in tabular format.

  • Content Management Displaying content stored in JSON format from content management systems.

  • Reporting Creating dynamic reports and dashboards from JSON data sources.

Browser Compatibility

This approach requires

  • Web Server Due to CORS restrictions, JSON files must be served via HTTP/HTTPS, not opened directly as local files.

  • jQuery Support Compatible with jQuery 1.5+ and all modern browsers (Chrome, Firefox, Safari, Edge).

  • JSON Support Native JSON parsing is supported in all modern browsers and IE8+.

Conclusion

Using jQuery's $.getJSON() method provides an efficient way to fetch JSON data and dynamically populate HTML tables. This approach enables real-time data updates, improves user experience, and creates scalable web applications that can handle varying data requirements without page reloads.

Updated on: 2026-03-16T21:38:54+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements