show json data in table using javascript

Show JSON Data in Table Using JavaScript

If you want to display your JSON data in a table format on your web page, you can easily do so with JavaScript. Here's how:

Step 1: Create a Table and a Head Row

The first step is to create an HTML table with a head row that will contain the column headings. You can do this using the <table>, <thead>, and <tr> tags:

<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Location</th>
    </tr>
  </thead>
</table>

Step 2: Parse Your JSON Data

The next step is to parse your JSON data using JavaScript. You can do this using the JSON.parse() method:

var myData = JSON.parse('[
  {"name": "John Smith", "age": 35, "location": "New York"},
  {"name": "Jane Doe", "age": 27, "location": "Los Angeles"},
  {"name": "Bob Johnson", "age": 42, "location": "Chicago"}
]');

Step 3: Loop Through Your Data and Add Rows to the Table

Finally, you can loop through your data and add rows to the table using JavaScript. You can do this using the <tbody> and <tr> tags:

var table = document.getElementById("myTable");
var tbody = document.createElement("tbody");

for (var i = 0; i < myData.length; i++) {
  var row = document.createElement("tr");
  
  var nameCell = document.createElement("td");
  nameCell.innerHTML = myData[i].name;
  row.appendChild(nameCell);
  
  var ageCell = document.createElement("td");
  ageCell.innerHTML = myData[i].age;
  row.appendChild(ageCell);
  
  var locationCell = document.createElement("td");
  locationCell.innerHTML = myData[i].location;
  row.appendChild(locationCell);
  
  tbody.appendChild(row);
}

table.appendChild(tbody);

And that's it! Your JSON data should now be displayed in a table on your web page.

Alternative Method: Use jQuery

If you're using jQuery on your web page, you can also use the $.each() method to loop through your JSON data and add rows to the table. Here's an example:

var myData = JSON.parse('[
  {"name": "John Smith", "age": 35, "location": "New York"},
  {"name": "Jane Doe", "age": 27, "location": "Los Angeles"},
  {"name": "Bob Johnson", "age": 42, "location": "Chicago"}
]');

$.each(myData, function(index, value) {
  var row = "<tr><td>" + value.name + "</td><td>" + value.age + "</td><td>" + value.location + "</td></tr>";
  $("#myTable tbody").append(row);
});

Using jQuery can make the process a bit simpler and more concise.

Remember to include the highlight.js library to display syntax highlighting for your code snippets!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe