Open Playground
JS Web APIsLesson #187

JavaScript Displaying JSON

After JSON has been parsed, the resulting JavaScript values can be displayed in HTML.

After JSON has been parsed, the resulting JavaScript values can be displayed in HTML.

You can display individual values, objects, arrays, lists, and tables.

Share

Displaying a Property

A parsed JSON object becomes a JavaScript object.

Object properties can be displayed with normal JavaScript syntax.

Example

Example Code

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
const person = {name: "John", age: 30};

myDisplayer(person);

Use JSON.stringify() to display the complete object as JSON text.

Example

Example Code

javascript
Try it Yourself
const person = {name: "John", age: 30};

let text = JSON.stringify(person)

myDisplayer(text);

Formatting JSON Text

The third parameter of JSON.stringify() can format the JSON with indentation.

Use an HTML element to preserve spaces and line breaks.

Example

Example Code

html
Try it Yourself
const person = { name: "John", age: 30, city: "New York" }; document.getElementById("demo").textContent = JSON.stringify(person, null, 2);
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

Example Code

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
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

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

Example Code

html
Try it Yourself
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);

}
The example creates one element for each array value.

Displaying an Array of Objects

JSON often contains an array of objects.

products.json

Example Code

javascript
Try it Yourself
[

  {"name":"Laptop","price":899},

  {"name":"Mouse","price":29},

  {"name":"Keyboard","price":79}

]

Use a loop to display a property from each object.

Example

Example Code

html
Try it Yourself
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);

}

Displaying JSON in a Table

An array of objects can be displayed as an HTML table.

Example

Example Code

html
Try it Yourself
| Product | Price |
| --- | --- |

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;

}

The example creates one table row for each product.


Displaying Nested JSON

JSON objects and arrays can contain nested values.

Example

Example Code

javascript
Try it Yourself
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

Example Code

html
Try it Yourself
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();
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.

PropertyUse
textContentDisplaying text and untrusted data
innerHTMLAdding HTML that your application controls

Do not insert untrusted JSON values directly into innerHTML.

The values could contain unwanted or dangerous HTML.

Safer

Example Code

javascript
Try it Yourself
element.textContent = customer.name;

Missing Properties

A JSON object might not contain every expected property.

The nullish coalescing operator can provide a default value.

Example

Example Code

javascript
Try it Yourself
const person = {name: "John"};

document.getElementById("demo").textContent =

person.city ?? "Unknown city";
The default value unknown city is used when the property is null or undefined.

Interactive Code Examples

JS Example 1

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const text = '{"name":"John","age":30,"city":"New York"}';


const person = JSON.parse(text);


document.getElementById("demo").textContent = person.name;

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const text = '{"name":"John","age":30,"city":"New York"}';


const person = JSON.parse(text);


document.getElementById("demo").textContent =

person.name + ", " + person.age + ", " + person.city;

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const person = {name: "John", age: 30};


myDisplayer(person);

JS Example 4

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const person = {name: "John", age: 30};



let text = JSON.stringify(person)



myDisplayer(text);

JS Example 5

html
Try it Yourself
JavaScript syntax and algorithm demonstration.
<pre id="demo"></pre>


<script>

const person = {

  name: "John",

  age: 30,

  city: "New York"

};


document.getElementById("demo").textContent =

JSON.stringify(person, null, 2);

</script>

JS Example 6

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const text = '["Ford","Volvo","BMW"]';


const cars = JSON.parse(text);


document.getElementById("demo").textContent = cars[0];