Rendering JSON Data into the DOM
JSON and the DOM meet constantly in real apps: you get data as JSON (from an API, a file, localStorage), and your job is to turn each item into visible elements.
const productsJson = '[{"id":1,"name":"Keyboard","price":49},{"id":2,"name":"Mouse","price":19}]';
const products = JSON.parse(productsJson);
const list = document.querySelector('#products');
list.innerHTML = ''; // clear any placeholder content
products.forEach(function (product) {
const item = document.createElement('li');
item.textContent = product.name + ', $' + product.price;
item.dataset.id = String(product.id);
list.append(item);
});
Needs a real #products element, so it's read-only here, you'll build the runnable version in the final project.
The pattern
- Get JSON (parsed from text, or from
await res.json()after afetch). - Loop over the parsed array with
.forEach/.map. - For each item,
createElement, set its content and attributes from that item's properties, thenappendit. - Clear a container first (
list.innerHTML = '') so re-rendering doesn't duplicate elements.
This same loop is how every JSON-driven UI works, a to-do list, a product grid, a chat log, only the shape of the JSON and the elements you create change.