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
- Get the JSON text (from an API, a file, or inline).
JSON.parse()it into objects and arrays.- Loop over the data and create elements.
- Insert them into the page.
A list from a JSON array
The playground below is a live page. Edit the JSON and press ▶ Run:
<!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.
<!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).
<!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:
function escapeHtml(text) {
return String(text)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
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 & Biscuits <em><new></em></li>
<li>Cups <em>6 "large"</em></li>
</ul>
A dropdown from JSON
The same idea works for any element — here, <option>s of a <select>:
<!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?
- el.innerHTML = value
- el.textContent = value
- document.write(value)
- eval(value)
For an array of objects with the same keys, what do the keys usually become in an HTML table?
- Rows
- Column headers
- Captions
- Nothing
What does escapeHtml("<b>") (as written in this lesson) return?
- <b>
- <b>
- b
- "b"