Tutorials Tonight
Write for Us

Display JSON Data in HTML Page


JSON format is highly used to store data in a structured way. Even data received from a server is in JSON format. Here we will see how to display JSON data in HTML page using JavaScript in form of tables and lists.

JSON data has a structure like a javascript object. Data is stored in key-value pairs, where the key is a string and value can be any type of data.

First, you may think to display these data directly as text on the webpage but this doesn't look appealing also is not readable.

SSo in this article, we will fetch JSON data from a local or remote server and display it in a better way.

display JSON data in HTML page

Display JSON data in HTML page using JavaScript

To start working with let our JSON data be following. Source link.

{
  "result": [
    {
      "name": "John",
      "marks":{
        "math":"78",
        "english":"90",
        ...
      }
    },
    {
      "name": "Mike",
      "marks":{
        "math":"67",
        "english":"86",
        ...
      }
    },
    ...
  ]
}

Now we will fetch this JSON data from the remote server and display it on the webpage.

To read JSON data from the local or remote servers we will use the fetch() method.

The fetch() method takes the URL of the JSON file as an argument and returns a Promise object.

After resolving the Promise object we will get the JSON data in the Response object.

fetch(URL)
  // get the JSON data
  .then(response => response.json())
  // use (display) the JSON data
  .then(data => console.log(data))

We have the JSON data in data stored in a variable. Now we can use it to display the data in the webpage.


1. Display JSON Data As List

To display the JSON data in a list we will create HTML elements dynamically and insert data in them.

Elements we need to create here are ul and li.

Before we start keep the data structure of JSON data in mind. The image below shows to get the first student name we have to use data.result[0].name and to get first student marks we have to use data.result[0].marks, where to access marks of math subject we have to use data.result[0].marks.math.

structure of JSON data

Keeping the above structure in mind we first create a ul element and assign it to a variable.

const mainUL = document.createElement('ul')

This ul element will be the main element any list element (li) will represent a student and their marks and will be created dynamically.

Now we can create a for loop that will iterate over the data.result array and create a li element for each student and set innerHTML of the li element to the student name.

for(let i = 0; i < data.result.length; i++) {
  const studentLI = document.createElement('li');
  studentLI.innerHTML = data.result[i].name;
}

Now create another list that will contain all the marks of the student and append it to the li element (studentLI) created just before.

for(let i = 0; i < data.result.length; i++) {
  const studentLI = document.createElement('li');
  studentLI.innerHTML = data.result[i].name;

  // create list for marks
  const marksUL = document.createElement('ul');
  for(var key in data.result[i].marks) {
    const marksLI = document.createElement('li');
    marksLI.innerHTML = key + ': ' + data.result[i].marks[key];
    marksUL.appendChild(marksLI);
  }

  // append marks list to studentLI
  studentLI.appendChild(marksUL);
}

Now we have created a list of students and their marks. Now we can append the ul element to the mainUL element.

// append studentLI to mainUL
mainUL.appendChild(studentLI);

Finally, append it to the body. Here is the complete code to display the list of students and their marks.

Example
<button onclick="showList()">Show List</button>

<script>
  function showList(){
    fetch("./lib/examples/students.json")
      .then(response => response.json())
      .then(data => createList(data));
  }
  
  function createList(data) {
    const mainUL = document.createElement('ol');
    for (let i = 0; i < data.result.length; i++) {
      const studentLI = document.createElement('li');
      studentLI.innerHTML = data.result[i].name;

      // create list for marks
      const marksUL = document.createElement('ul');
      for (var key in data.result[i].marks) {
        const marksLI = document.createElement('li');
        marksLI.innerHTML = key + ': ' + data.result[i].marks[key];
        marksUL.appendChild(marksLI);
      }

      // append marks list to studentLI
      studentLI.appendChild(marksUL);
      // append student list to mainUL
      mainUL.appendChild(studentLI);
    }
    // append mainUL to body
    document.body.appendChild(mainUL);
  }
</script>

Output:

display JSON data as list

2. Display JSON Data As Table

To display the JSON data in a table we will create a function that takes JSON data as an argument and creates a table and append it to the body.

In the function createtable() create the basic structure of the table so that we have the heading of the table as 'name' and 'marks'. Below these marks create another list to show the subject as shown in the code below.

var table = "<table border=1>";
// add a row for name and marks
table += `<tr>
            <th>Name</th>
            <th colspan="4">Marks</th>
          </tr>`;
// now add another row to show subject
table += `<tr>
            <th></th>
            <th>Math</th>
            <th>English</th>
            <th>Chemistry</th>
            <th>Physics</th>
          </tr>`;

Now we can create a for loop that will iterate over the data.result array and create a tr element for each student and set innerHTML of the tr element to the student name.

// now loop through students
// show their name and marks
var tr = "";
for(let i = 0; i < data.result.length; i++) {
  tr += "<tr>";
  tr += `<td>${data.result[i].name}</td>`;
  for (var key in data.result[i].marks) {
    tr += `<td>${data.result[i].marks[key]}</td>`;
  }
  tr += "</tr>"
}

Finally, append the table to the body. Here is the complete Javascript code for fetching JSON data and displaying it as a table.

Example
function showTable(){
  fetch("./lib/examples/students.json")
    .then(response => response.json())
    .then(data => createTable(data));
}
    
function createTable(data) {
var table = "<table border=1>";
// add a row for name and marks
table += `<tr>
            <th>Name</th>
            <th colspan="4">Marks</th>
          </tr>`;
// now add another row to show subject
table += `<tr>
            <th></th>
            <th>Math</th>
            <th>English</th>
            <th>Chemistry</th>
            <th>Physics</th>
          </tr>`;
// now loop through students
// show their name and marks
var tr = "";
for(let i = 0; i < data.result.length; i++) {
  tr += "<tr>";
  tr += `<td>${data.result[i].name}</td>`;
  for (var key in data.result[i].marks) {
    tr += `<td>${data.result[i].marks[key]}</td>`;
  }
  tr += "</tr>"
}
table += tr + "</table>";

  // append table to body
  document.body.innerHTML += table;
}

Output:

display JSON data as a table

Conclusion

In this short tutorial, we saw how to fetch and display JSON data in HTML pages using javascript. We displayed data as a list and table with a complete explanation of the code.