TExcelTAD
Home › JSON › JSON to HTML

JSON to HTML

A very common job in web development: you receive JSON data and need to show it on a page — as a list, a table or a set of cards. This lesson shows how to turn JSON into HTML safely with plain JavaScript.

The basic recipe

  1. Get the JSON text (from an API, a file, or inline).
  2. JSON.parse() it into objects and arrays.
  3. Loop over the data and create elements.
  4. Insert them into the page.

A list from a JSON array

The playground below is a live page. Edit the JSON and press ▶ Run:

html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: system-ui, sans-serif">
  <h3>Today's tasks</h3>
  <ul id="tasks"></ul>

  <script>
    const json = '["Write the report", "Review pull request", "Water the plants"]';
    const tasks = JSON.parse(json);

    const ul = document.getElementById("tasks");
    for (const task of tasks) {
      const li = document.createElement("li");
      li.textContent = task;
      ul.appendChild(li);
    }
    console.log(tasks.length + " tasks rendered");
  </script>
</body>
</html>

A table from an array of objects

An array of objects with the same keys maps perfectly to a table: keys become column headers, objects become rows.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: system-ui, sans-serif; }
    table { border-collapse: collapse; }
    th, td { border: 1px solid #ccc; padding: 6px 12px; text-align: left; }
    th { background: #f0a30a; color: white; }
    td.num { text-align: right; }
  </style>
</head>
<body>
  <div id="out"></div>
  <script>
    const json = `[
      {"product": "Green Tea", "category": "Drinks", "price": 4.5},
      {"product": "Rice Cooker", "category": "Kitchen", "price": 59},
      {"product": "Notebook", "category": "Office", "price": 3.25}
    ]`;
    const rows = JSON.parse(json);
    const columns = Object.keys(rows[0]);

    const table = document.createElement("table");
    const header = table.insertRow();
    for (const col of columns) {
      const th = document.createElement("th");
      th.textContent = col;
      header.appendChild(th);
    }
    for (const row of rows) {
      const tr = table.insertRow();
      for (const col of columns) {
        const td = tr.insertCell();
        const value = row[col];
        td.textContent = typeof value === "number" ? value.toFixed(2) : value;
        if (typeof value === "number") td.className = "num";
      }
    }
    document.getElementById("out").appendChild(table);
  </script>
</body>
</html>

textContent vs innerHTML

It's tempting to build HTML with template strings and innerHTML. That's fine for trusted, hard-coded text, but dangerous for data: if a JSON string contains HTML, the browser will run it. This is called cross-site scripting (XSS).

html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: system-ui, sans-serif">
  <p>Unsafe (innerHTML): <span id="unsafe"></span></p>
  <p>Safe (textContent): <span id="safe"></span></p>
  <script>
    // Imagine this comment came from another user via an API
    const data = JSON.parse('{"comment": "<b>Nice!</b> <img src=x onerror=\\"console.log(\'script ran!\')\\">"}');

    document.getElementById("unsafe").innerHTML = data.comment;   // runs the onerror code
    document.getElementById("safe").textContent = data.comment;   // shows it as text
  </script>
</body>
</html>

Run it and look at the console under the frame: the "unsafe" version executed code that came from the data.

Method Data treated as Use for
el.textContent = value Plain text Any data from JSON
document.createElement(...) Structure you control Building lists, tables, cards
el.innerHTML = value HTML markup Only trusted, static markup

Escaping when you must build strings

Sometimes generating an HTML string is the simplest option (for example on a server). Then escape the five special characters first. This function works anywhere — even outside a browser:

js · try it yourself
function escapeHtml(text) {
  return String(text)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

const products = JSON.parse('[{"name": "Tea & Biscuits", "note": "<new>"}, {"name": "Cups", "note": "6 \\"large\\""}]');

const html = "<ul>\n" + products
  .map((p) => `  <li>${escapeHtml(p.name)} <em>${escapeHtml(p.note)}</em></li>`)
  .join("\n") + "\n</ul>";
console.log(html);
<ul>
  <li>Tea &amp; Biscuits <em>&lt;new&gt;</em></li>
  <li>Cups <em>6 &quot;large&quot;</em></li>
</ul>

A dropdown from JSON

The same idea works for any element — here, <option>s of a <select>:

html · try it yourself
<!DOCTYPE html>
<html>
<body style="font-family: system-ui, sans-serif">
  <label>Country: <select id="country"></select></label>
  <p id="picked"></p>
  <script>
    const countries = JSON.parse('[{"code": "VN", "name": "Vietnam"}, {"code": "JP", "name": "Japan"}, {"code": "FR", "name": "France"}]');
    const select = document.getElementById("country");
    for (const c of countries) {
      select.add(new Option(c.name, c.code));
    }
    select.addEventListener("change", () => {
      document.getElementById("picked").textContent = "You picked: " + select.value;
    });
  </script>
</body>
</html>

Tip: Frameworks like React and Vue escape data for you when you write {value} or {{ value }} — one of the reasons they are popular for rendering JSON data.

Test yourself

Which is the safest way to show a string from JSON data in an element?

  1. el.innerHTML = value
  2. el.textContent = value
  3. document.write(value)
  4. eval(value)

For an array of objects with the same keys, what do the keys usually become in an HTML table?

  1. Rows
  2. Column headers
  3. Captions
  4. Nothing

What does escapeHtml("<b>") (as written in this lesson) return?

  1. <b>
  2. &lt;b&gt;
  3. b
  4. &quot;b&quot;