JSON & the DOM

Lesson 5 of 6

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

  1. Get JSON (parsed from text, or from await res.json() after a fetch).
  2. Loop over the parsed array with .forEach/.map.
  3. For each item, createElement, set its content and attributes from that item's properties, then append it.
  4. 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.

📝 JSON-to-DOM Quiz

Passing score: 70%
  1. 1.What is the first step when turning a JSON array into DOM elements?

  2. 2.Setting list.innerHTML = '' before re-rendering helps avoid duplicate elements on a second render.

  3. 3.Looping over a parsed array and calling document.____ for each item is how you build DOM elements from JSON.