How to fetch and display JSON data in HTML using JavaScript

avatar
Borislav Hadzhiev

Last updated: May 30, 2023
7 min

banner

# Table of Contents

  1. Fetching and Displaying JSON data directly in HTML using JavaScript
  2. Fetching, Formatting and Displaying JSON data in HTML using JavaScript
  3. Fetching, Formatting and Displaying JSON data in HTML using innerHTML
  4. Fetching and Displaying JSON data in a Table in HTML using JavaScript

# Fetching and Displaying JSON data directly in HTML using JavaScript

You can use the pre element if you need to display JSON data directly on your page.

The <pre> HTML element represents preformatted text which is to be presented exactly as written in the HTML file.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <h2>bobbyhadz.com</h2> <br /> <br /> <pre id="json-data"></pre> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const arr = [ {id: 1, name: 'Alice', age: 29}, {id: 2, name: 'Bobby Hadz', age: 30}, {id: 3, name: 'Carl', age: 31}, ]; const preElement = document.getElementById('json-data'); preElement.style.fontSize = '18px'; preElement.innerHTML = JSON.stringify(arr, null, 2);

display json data in html using pre element

Notice that we used a pre element in our HTML.

index.html
<pre id="json-data"></pre>

The pre element represents preformatted text which is to be presented exactly as written in the HTML file.

We used the JSON.stringify() method to convert the JavaScript array to a JSON string and used 2 spaces for the indentation.

index.js
const arr = [ {id: 1, name: 'Alice', age: 29}, {id: 2, name: 'Bobby Hadz', age: 30}, {id: 3, name: 'Carl', age: 31}, ]; const preElement = document.getElementById('json-data'); preElement.style.fontSize = '18px'; preElement.innerHTML = JSON.stringify(arr, null, 2);

If you need to parse a JSON string into a native JavaScript array or object, use the JSON.parse method.

index.js
const arr = [ {id: 1, name: 'Alice', age: 29}, {id: 2, name: 'Bobby Hadz', age: 30}, {id: 3, name: 'Carl', age: 31}, ]; const jsonString = JSON.stringify(arr); const arrayAgain = JSON.parse(jsonString); console.log(Array.isArray(arrayAgain)); // 👉️ true
  • The JSON.stringify() method converts a JavaScript array or object to a string.
  • The JSON.parse() method parses a JSON string into a native JavaScript array or object.

Here is an example that uses 4 spaces for the indentation parameter.

index.js
preElement.innerHTML = JSON.stringify(arr, null, 4);

display json data in html using 4 spaces indentation

If you don't specify the third argument in the call to JSON.stringify(), the JSON will be displayed on a single line.

index.js
preElement.innerHTML = JSON.stringify(arr);

json displayed on single line

If you need to fetch the JSON data from a remote API before you display it in your HTML, use the built-in fetch() method.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <h2>bobbyhadz.com</h2> <br /> <br /> <pre id="json-data"></pre> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
async function getUsers() { try { const response = await fetch( 'https://jsonplaceholder.typicode.com/users', { method: 'GET', }, ); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.log(error); } } getUsers().then(data => { console.log(data); const preElement = document.getElementById('json-data'); preElement.style.fontSize = '18px'; preElement.innerHTML = JSON.stringify(data, null, 2); });

fetch and display json data directly in html

The getUser() function makes an HTTP GET request to a remote API and retrieves some data.

The function uses the async/await syntax, so it returns a Promise.

We used the .then() syntax to wait for the Promise to resolve before rendering the JSON data in the HTML.

# Fetching, Formatting and Displaying JSON data in HTML using JavaScript

If you need to fetch, format and display the JSON data in HTML using JavaScript:

  1. Use the fetch() method to fetch the data from the remote API.
  2. Iterate over the fetched data.
  3. Create DOM elements that render the fetched data and append them to the DOM.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <h2>bobbyhadz.com</h2> <br /> <br /> <div id="container"></div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
// 1) Fetch data from remote API async function getUsers() { try { const response = await fetch( 'https://jsonplaceholder.typicode.com/users', { method: 'GET', }, ); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.log(error); } } // 2) Render the data in your HTML getUsers().then(data => { console.log(data); const ol = document.createElement('ol'); data.forEach(user => { const li = document.createElement('li'); li.innerHTML = user.name; li.style.fontSize = '22px'; const ul = document.createElement('ul'); const company = document.createElement('li'); company.innerHTML = `Company: ${user.company.name}`; const city = document.createElement('li'); city.innerHTML = `City: ${user.address.city}`; const email = document.createElement('li'); email.innerHTML = `Email: ${user.email}`; const phone = document.createElement('li'); phone.innerHTML = `Phone: ${user.phone}`; ul.append(...[company, city, email, phone]); li.appendChild(ul); ol.appendChild(li); }); const container = document.getElementById('container'); container.appendChild(ol); });

fetch format and render json data in html

The API from the examples responds with an array of objects that look as follows.

index.js
{ "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } }

The array contains 10 objects with the specified format.

The first step is to fetch the array from the remote API using the fetch() method.

Once we've parsed the JSON string into a native JavaScript Array, we create an ordered list (ol) element.

index.js
getUsers().then(data => { console.log(data); const ol = document.createElement('ol'); // ... });

The ol element is used to render the names of the users in an ordered list.

render names of users in ordered list

The next step is to iterate over the array of users with the Array.forEach method.

index.js
getUsers().then(data => { console.log(data); const ol = document.createElement('ol'); data.forEach(user => { const li = document.createElement('li'); li.innerHTML = user.name; li.style.fontSize = '22px'; const ul = document.createElement('ul'); const company = document.createElement('li'); company.innerHTML = `Company: ${user.company.name}`; const city = document.createElement('li'); city.innerHTML = `City: ${user.address.city}`; const email = document.createElement('li'); email.innerHTML = `Email: ${user.email}`; const phone = document.createElement('li'); phone.innerHTML = `Phone: ${user.phone}`; ul.append(...[company, city, email, phone]); li.appendChild(ul); ol.appendChild(li); }); const container = document.getElementById('container'); container.appendChild(ol); });
  1. We first create a li element for the name of each user.
  2. Then we create a ul (unordered list) element for the additional details of each user.
  3. The next step is to create li elements for specific properties of each user (e.g. company, city, email, phone, etc).

Once we've created the li elements, we append them to the ul.

index.js
ul.append(...[company, city, email, phone]);

We then append the unordered list to the li elements that store the name of each user and append the li elements to the ol (ordered list).

index.js
li.appendChild(ul); ol.appendChild(li);

Once you've constructed the ordered list, append it to the container element.

index.js
const container = document.getElementById('container'); container.appendChild(ol);

You might be working with data that is formatted differently but the concept is the same:

  1. You have to fetch the data from the remote API.
  2. You have to use the document.createElement() method to create DOM elements that render the fetched data.
  3. You have to append the created elements to the DOM.

# Fetching, Formatting and Displaying JSON data in HTML using innerHTML

If you have very nested DOM structures, it might be easier to manually write the HTML in a template literal string instead of using the document.createElement method.

Here is an example that achieves the same result using innerHTML.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <h2>bobbyhadz.com</h2> <br /> <br /> <div id="container"></div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
async function getUsers() { try { const response = await fetch( 'https://jsonplaceholder.typicode.com/users', { method: 'GET', }, ); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.log(error); } } getUsers().then(data => { console.log(data); let ol = '<ol>'; data.forEach(user => { ol += ` <li style="font-size: 22px;"> ${user.name} <ul> <li>Company: ${user.company.name}</li> <li>City: ${user.address.city}</li> <li>Email: ${user.email}</li> <li>Phone: ${user.phone}</li> </ul> </li> `; }); ol += '</ol>'; const container = document.getElementById('container'); container.innerHTML = ol; });

The JavaScript code is a bit more compact.

Note that the template literal string is wrapped in backticks `, and not single quotes.

The dollar sign and curly braces ${} syntax enables you to interpolate variables in the string.

The code sample produces the same HTML as in the previous example.

display json data in html using innerhtml property

However, it is a bit easier to read and more direct because we basically write HTML using JavaScript.

# Fetching and Displaying JSON data in a Table in HTML using JavaScript

The same approach can be used if you need to fetch and display the JSON data in a table.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } table td, table th { border: 1px solid black; } </style> </head> <body> <h2>bobbyhadz.com</h2> <br /> <br /> <div id="container"></div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
async function getUsers() { try { const response = await fetch( 'https://jsonplaceholder.typicode.com/users', { method: 'GET', }, ); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.log(error); } } getUsers().then(data => { console.log(data); let table = '<table style="border-collapse: collapse;">'; table += ` <thead> <tr> <th>Name</th> <th>Company</th> <th>City</th> <th>Email</th> </tr> </thead> <tbody> `; data.forEach(user => { table += ` <tr> <td>${user.name}</td> <td>${user.company.name}</td> <td>${user.address.city}</td> <td>${user.email}</td> </tr> `; }); table += ` </tbody> </table> `; const container = document.getElementById('container'); container.innerHTML = table; });

fetch and display json data in table in html

We first initialized the table string.

index.js
let table = '<table style="border-collapse: collapse;">';

And then added the thead element with the column names to the string.

index.js
table += ` <thead> <tr> <th>Name</th> <th>Company</th> <th>City</th> <th>Email</th> </tr> </thead> <tbody> `;

The next step is to iterate over the array of users.

index.js
data.forEach(user => { table += ` <tr> <td>${user.name}</td> <td>${user.company.name}</td> <td>${user.address.city}</td> <td>${user.email}</td> </tr> `; });

On each iteration, we create a new table row element and add the data for each column.

Make sure to close the tbody and table elements once you're done.

index.js
table += ` </tbody> </table> `;

Lastly, set the innerHTML of the container div to the table HTML string.

index.js
const container = document.getElementById('container'); container.innerHTML = table;

fetch and display json data in table in html

I've also written an article on Convert an HTML table to JSON and export it to a file in JS.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.