JS JSON HTML
In this page:
const object = JSON.parse(jsonText);
element.innerHTML = object.property;
Building Elements from JSON with the DOM API
Looping over a parsed JSON array and, for each item, calling document.createElement() and setting properties (like textContent) builds real DOM elements safely -- textContent in particular ensures any text is treated as plain text, never interpreted as HTML.
Example: Building Elements from JSON with the DOM API
const items = [{ name: "Sam" }, { name: "Amit" }];
const list = document.createElement("ul");
items.forEach(item => {
const li = document.createElement("li");
li.textContent = item.name; // treated as plain text, never HTML
list.appendChild(li);
});
document.body.appendChild(list);
Building an HTML String with Template Literals
Combining .map() with a template literal produces an HTML string for each JSON item, then .join("") combines them into one string ready to insert via innerHTML -- more concise than building elements individually, but requires manual escaping for any untrusted content.
Example: Building an HTML String with Template Literals
// Declare the constant `items`, set to `[{ name: "Sam" }, { name: "Amit" }]`
// Declare the constant `items`, set to `[{ name: "Sam" }, { name: "Amit" }]`
const items = [{ name: "Sam" }, { name: "Amit" }];
// Declare the constant `html`, set to `items.map(item => `<li>${item.name}</li>`).join("")`
// Declare the constant `html`, set to `items.map(item => `<li>${item.name}</li>`).join("")`
const html = items.map(item => `<li>${item.name}</li>`).join("");
// Assign `<ul>${html}</ul>` to `document.body.innerHTML`
// Assign `<ul>${html}</ul>` to `document.body.innerHTML`
document.body.innerHTML = `<ul>${html}</ul>`;
Handling an Empty JSON Array
A JSON response might legitimately contain an empty array -- rendering code should explicitly check for this and show a clear "no results" or "nothing here yet" message, rather than silently leaving a blank area that looks like a bug rather than an intentional empty state.
Example: Handling an Empty JSON Array
// Declare the constant `items`, set to `[]`
// Declare the constant `items`, set to `[]`
const items = [];
// Assign `items.length` to `document.body.innerHTML`
// Assign `items.length` to `document.body.innerHTML`
document.body.innerHTML = items.length
? items.map(item => `<p>${item.name}</p>`).join("")
: "<p>No results</p>";
Updating the DOM Efficiently on Data Changes
Rebuilding an entire list from scratch every time the underlying JSON data changes even slightly is wasteful -- for frequently-updating data, targeted updates (changing just the specific elements affected) or a lightweight diffing approach performs noticeably better than a full teardown-and-rebuild.
Example: Updating the DOM Efficiently on Data Changes
function updateItem(id, newText) {
document.querySelector(`[data-id="${id}"]`).textContent = newText; // targeted update, not a full rebuild
}
console.log(typeof updateItem);
A Complete Fetch-to-HTML Example
Combining everything: fetching JSON, handling the loading and error states, checking for an empty result, and safely rendering the data as HTML -- the complete, realistic pipeline behind rendering almost any dynamic, data-driven section of a modern web page.
Example: A Complete Fetch-to-HTML Example
// Assign "<p>Loading...</p>" to `document.body.innerHTML`
// Assign "<p>Loading...</p>" to `document.body.innerHTML`
document.body.innerHTML = "<p>Loading...</p>";
// Define the method `fetch` taking `"items.php"`
// Define the method `fetch` taking `"items.php"`
fetch("items.php")
// On success, run this with the resolved value as `r`
// On success, run this with the resolved value as `r`
.then(r => r.json())
// On success, run this with the resolved value as `items`
// On success, run this with the resolved value as `items`
.then(items => {
// Assign `items.length` to `document.body.innerHTML`
// Assign `items.length` to `document.body.innerHTML`
document.body.innerHTML = items.length
? items.map(i => `<p>${i.name}</p>`).join("")
: "<p>No results</p>";
})
.catch(() => document.body.innerHTML = "<p>Failed to load</p>");
- Inserting JSON-derived text directly into innerHTML without escaping it, opening an XSS vulnerability if that data ever contains user-generated content with embedded HTML or script tags.
- Rebuilding the entire list from scratch on every small data update, when updating just the changed elements would be far more efficient.
- Forgetting to handle an empty array from the JSON response, leaving a blank area instead of a clear "no results" message.
- JSON data is typically rendered into HTML by looping over it and either building DOM elements or an HTML string for each item.
- Any JSON-derived text that could contain user-generated content should be inserted via textContent (or escaped) rather than raw innerHTML, to avoid XSS.
- Template literals combined with .map().join("") are a common concise pattern for building an HTML string from an array of JSON objects.
Rendering fetched JSON as HTML uses only standard DOM methods, supported in every modern browser.
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML