Last updated: Apr 4, 2024
Reading time·7 min
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.
<!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.
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);
Notice that we used a pre
element in our 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 then used 2 spaces for the indentation.
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.
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
JSON.stringify()
method converts a JavaScript array or object to a
string.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.
preElement.innerHTML = JSON.stringify(arr, null, 4);
If you don't specify the third argument in the call to JSON.stringify()
, the
JSON will be displayed on a single line.
preElement.innerHTML = JSON.stringify(arr);
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.
<!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.
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); });
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.
If you need to fetch, format and display the JSON data in HTML using JavaScript:
fetch()
method to fetch the data from the remote API.Here is the HTML for the example.
<!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.
// 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); });
The API from the examples responds with an array of objects that look as follows.
{ "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.
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.
The next step is to iterate over the array of users with the Array.forEach() method.
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); });
li
element for the name
of each user.ul
(unordered list) element for the additional details of
each user.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
.
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).
li.appendChild(ul); ol.appendChild(li);
Once you've constructed the ordered list, append it to the container element.
const container = document.getElementById('container'); container.appendChild(ol);
You might be working with data that is formatted differently but the concept is the same:
document.createElement()
method to create DOM elements
that render the fetched data.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
.
<!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.
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.
However, it is a bit easier to read and more direct because we basically write 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.
<!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.
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; });
We first initialized the table
string.
let table = '<table style="border-collapse: collapse;">';
And then added the thead
element with the column names to the string.
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.
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.
table += ` </tbody> </table> `;
Lastly, set the innerHTML
of the container
div to the table HTML string.
const container = document.getElementById('container'); container.innerHTML = table;
I've also written an article on Convert an HTML table to JSON and export it to a file in JS.
You can learn more about the related topics by checking out the following tutorials: