Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP W3.CSS C C++ C# HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

JS Tutorial

JS Home JS Introduction JS Where To JS Output JS Syntax JS Operators JS If Conditions JS Loops JS Strings JS Numbers JS Functions JS Timers JS Objects JS Scope JS Dates JS Temporal  New JS Arrays JS Sets JS Maps JS Iterations JS Math JS RegExp JS Data Types JS Errors JS Debugging JS Style Guide JS Reference JS Projects  New JS Versions JS HTML DOM JS HTML Events JS HTML First

JS Advanced

JS Functions JS Objects JS Classes JS JSON JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Browser API JS Web API JS Graphics

Old Technologies

JS AJAX JS jQuery JS JSONP

JS Examples

JS Examples

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 textContent for plain text and untrusted data.
  • Do not call JSON.parse() after response.json().


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->