JavaScript Displaying JSON
After JSON has been parsed, the resulting JavaScript values can be displayed in HTML.
You can display individual values, objects, arrays, lists, and tables.
Displaying a Property
A parsed JSON object becomes a JavaScript object.
Object properties can be displayed with normal JavaScript syntax.
Example
const text = '{"name":"John","age":30,"city":"New York"}';
const person = JSON.parse(text);
document.getElementById("demo").textContent = person.name;
The example displays the value of the name property.
Displaying Multiple Properties
Multiple properties can be combined into one text value.
Example
const text = '{"name":"John","age":30,"city":"New York"}';
const person = JSON.parse(text);
document.getElementById("demo").textContent =
person.name + ", " + person.age + ", " + person.city;
Displaying an Object
Displaying an object directly does not show all its properties.
Example
const person = {name: "John", age: 30};
document.getElementById("demo").textContent = person;
The result is normally:
[object Object]
Use JSON.stringify() to display the complete object as JSON text.
Example
const person = {name: "John", age: 30};
document.getElementById("demo").textContent =
JSON.stringify(person);
Formatting JSON Text
The third parameter of JSON.stringify() can format the JSON with indentation.
Use an HTML <pre> element to preserve spaces and line breaks.
Example
<pre id="demo"></pre>
<script>
const person = {
name: "John",
age: 30,
city: "New York"
};
document.getElementById("demo").textContent =
JSON.stringify(person, null, 2);
</script>
The number 2 adds two spaces of indentation for each level.
Displaying a JSON Array
A parsed JSON array becomes a JavaScript array.
Array values can be accessed by their index numbers.
Example
const text = '["Ford","Volvo","BMW"]';
const cars = JSON.parse(text);
document.getElementById("demo").textContent = cars[0];
Array indexes start at zero.
Displaying All Array Values
A for...of loop can read every value in an array.
Example
const text = '["Ford","Volvo","BMW"]';
const cars = JSON.parse(text);
let output = "";
for (const car of cars) {
output += car + "\n";
}
document.getElementById("demo").textContent = output;
Use a <pre> element to display the line breaks.
Displaying an Array as a List
JavaScript can create HTML elements for the values in a JSON array.
Example
<ul id="demo"></ul>
<script>
const text = '["Ford","Volvo","BMW"]';
const cars = JSON.parse(text);
const list = document.getElementById("demo");
for (const car of cars) {
const item = document.createElement("li");
item.textContent = car;
list.appendChild(item);
}
</script>
The example creates one <li> element for each array value.
Displaying an Array of Objects
JSON often contains an array of objects.
products.json
[
{"name":"Laptop","price":899},
{"name":"Mouse","price":29},
{"name":"Keyboard","price":79}
]
Use a loop to display a property from each object.
Example
<ul id="demo"></ul>
<script>
const text = `[
{"name":"Laptop","price":899},
{"name":"Mouse","price":29},
{"name":"Keyboard","price":79}
]`;
const products = JSON.parse(text);
const list = document.getElementById("demo");
for (const product of products) {
const item = document.createElement("li");
item.textContent = product.name + ": $" + product.price;
list.appendChild(item);
}
</script>
Displaying JSON in a Table
An array of objects can be displayed as an HTML table.
Example
<table id="demo" class="ws-table-all">
<tr>
<th>Product</th>
<th>Price</th>
</tr>
</table>
<script>
const products = [
{name: "Laptop", price: 899},
{name: "Mouse", price: 29},
{name: "Keyboard", price: 79}
];
const table = document.getElementById("demo");
for (const product of products) {
const row = table.insertRow();
const nameCell = row.insertCell();
const priceCell = row.insertCell();
nameCell.textContent = product.name;
priceCell.textContent = "$" + product.price;
}
</script>
The example creates one table row for each product.
Displaying Nested JSON
JSON objects and arrays can contain nested values.
Example
const text = `{
"name": "John",
"address": {
"city": "New York",
"country": "USA"
}
}`;
const person = JSON.parse(text);
document.getElementById("demo").textContent =
person.address.city;
Use each property name to move through the nested object.
Loading and Displaying JSON
The fetch() method can load JSON from a file or server.
The parsed data can then be displayed in HTML.
Example
<p id="demo"></p>
<script>
async function loadCustomer() {
try {
const response = await fetch("customer.json");
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const customer = await response.json();
document.getElementById("demo").textContent =
customer.name + ", " + customer.city;
}
catch(err) {
document.getElementById("demo").textContent = err.message;
}
}
loadCustomer();
</script>
The response.json() method already parses the JSON.
Do not pass its result to JSON.parse().
textContent or innerHTML?
The textContent property displays values as plain text.
The innerHTML property interprets its value as HTML.
| Property | Use |
|---|---|
textContent |
Displaying text and untrusted data |
innerHTML |
Adding HTML that your application controls |
Do not insert untrusted JSON values directly into innerHTML.
The values could contain unwanted or dangerous HTML.
Safer
element.textContent = customer.name;
Potentially Unsafe
element.innerHTML = customer.name;
Missing Properties
A JSON object might not contain every expected property.
The nullish coalescing operator can provide a default value.
Example
const person = {name: "John"};
document.getElementById("demo").textContent =
person.city ?? "Unknown city";
The default value is used when the property is null or undefined.
Displaying JSON Summary
- Parsed JSON values can be displayed with normal JavaScript.
- Use property names to display values from objects.
- Use index numbers or loops to display array values.
- Arrays of objects can be displayed as lists or tables.
- Use
JSON.stringify()to display a complete object as JSON text. - Use
textContentfor plain text and untrusted data. - Do not call
JSON.parse()afterresponse.json().