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


JSON (JavaScript Object Notation) has become popular and offers a lightweight and clean−to−read layout for replacing information between a server and a web application. With the assistance of jQuery, an effective JavaScript library, you could easily fetch statistics from a JSON document and display it on an HTML desk. To run the code nearby, a web server is required. Alternatively, a code editor with a live server plugin can be employed.

Syntax

$.getJSON()

AJAX requests can be utilized to retrieve JSON data from files through this function.

The function takes two arguments:

URL: The primary argument is the URL of the JSON document or API endpoint from which we want to retrieve records. it is able to be a relative or absolute URL.

Data: The second argument is an elective parameter that permits us to send extra statistics along with the request. This parameter may be an object or a string in the query string layout.

$.each(data, function(index, item)

The callback function performs operations on each JSON array element using this approach. The index and item parameters represent the current index and object in the array, respectively. You can perform operations or access properties of the item object within the $.each() loop.

Example

The provided code is an HTML document that displays JSON data in an HTML table using JavaScript and jQuery. It receives JSON data from a file called "jsonexdata.json" and dynamically generates table rows and columns relying on the information.

Create a JSON document:

Create a separate file named jasonexdata.json and populate it with sample records in JSON format. In this case, let's assume that the JSON record contains an array of items, each representing the information of a person along with their funding quantity.

We want to have the "jsonexdata.json" file inside the identical directory as the HTML file to ensure that the code works.

Example

[
  {
    "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"
  }
]

Algorithm

  • The <table> element forms tables and its id attribute is titled 'data−table'.

  • The table header is defined within the tag, containing four columns: "Name", "Email", "Phone", and "Investment".

  • The table body is defined within the tag. This is where the JSON data will be inserted dynamically.

  • The `<script>` tags hold the jQuery code.

  • This function awaits the completion of the DOM loading process before proceeding with the code.

  • The $.getJSON() function enables the retrieval of JSON data from 'jsonexdata.json'.

  • The retrieved data is iterated over using the $.each() function.

  • For each person object in the JSON data, a new table row (<tr>) is created.

  • Table cells (<td>) are created and filled with the corresponding data from the person object.

  • The row is incorporated into the table body via the tableBody.append(row) procedure.

Example

<!DOCTYPE html>
<html>
<head>
  <title>Example:Display json Data to HTML Table</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
  /* CSS styles for the page */
  body {
    font-family: Arial, sans-serif;
  }

  h1 {
    text-align: center;
    color: #333;
  }

  table {
    width: 100%;
    border-collapse: collapse;
    border: 2px double #ddd;
  }

  th, td {
    padding: 10px 15px;
    text-align: left;
    color: #fff; /* Set the text color for table cells */
    border: 2px double #ddd;
    background-color: #454b4e; /* Set your desired color here */
    font-size: 24px;
  }

  th {
    background-color: #f2f2f2;
    font-size: 30px;
    font-weight: bold;
    text-align: center;
    color: #333; /* Set the text color for table headers */
  }

  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>
  <!-- JavaScript code using jQuery -->
  <script>
    $(document).ready(function() {
      // Retrieve JSON data from "jsonexdata.json" file
      $.getJSON("jsonexdata.json", function(data) {
        var tableBody = $("#data-table tbody");

        // Iterate over each person object in the JSON data
        $.each(data, function(index, person) {
          var row = $("<tr></tr>"); // Create a new table row

          // Create table cells and fill them with the person's data
          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); // Add the row to the table body
        });
      });
    });
  </script>
</body>
</html>

Conclusion

Acquiring information from a JSON file enables dynamic and immediate updates to the HTML table’s data. By using JSON files, data can be easily reproduced and shared throughout diverse pages or components without any hassle.

The ability to reuse data streamlines data management and simplifies application development., enabling scalability when dealing with varying data requirements.

Updated on: 10-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements