Skip to content

JSON Http

A primary use of JSON is to fetch data from a web server (API) and use it within a web page or application.

This chapter demonstrates how to request and process JSON data using the modern fetch API in JavaScript.

The fetch API provides a modern, powerful, and flexible interface for fetching resources, including JSON data from APIs. It uses Promises, making asynchronous operations easier to manage, especially with async/await syntax.

Example: Fetching and Displaying Menu Data

Section titled “Example: Fetching and Displaying Menu Data”

Imagine you have a file named menu.json on your server with the following content:

[
{
"display": "JavaScript Basics",
"url": "/tutorials/javascript/basics"
},
{
"display": "HTML Fundamentals",
"url": "/tutorials/html/fundamentals"
},
{
"display": "CSS Styling",
"url": "/tutorials/css/styling"
}
]

Here’s how you can fetch this data and display it as a list of links on your web page:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON Fetch Example</title>
</head>
<body>
<h1>Tutorial Menu</h1>
<div id="menuContainer">Loading menu...</div>
<p id="errorContainer" style="color: red;"></p>
<script>
const menuContainer = document.getElementById('menuContainer');
const errorContainer = document.getElementById('errorContainer');
const menuUrl = 'menu.json'; // Path to your JSON file or API endpoint
async function fetchMenu() {
try {
// 1. Make the request using fetch
const response = await fetch(menuUrl);
// 2. Check if the response status is OK (e.g., 200)
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// 3. Parse the response body as JSON
// response.json() returns a promise that resolves with the parsed JSON data
const menuItems = await response.json();
// 4. Process the JSON data (display it)
displayMenu(menuItems);
} catch (error) {
// Handle any errors during fetch or parsing
console.error('Failed to fetch menu:', error);
menuContainer.innerHTML = ''; // Clear loading message
errorContainer.textContent = `Error loading menu: ${error.message}`;
}
}
function displayMenu(items) {
// Clear the loading message
menuContainer.innerHTML = '';
if (!Array.isArray(items)) {
errorContainer.textContent = 'Invalid menu data format.';
return;
}
// Create a list element
const ul = document.createElement('ul');
// Create list items for each menu item
items.forEach(item => {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = item.url;
a.textContent = item.display;
li.appendChild(a);
ul.appendChild(li);
});
// Add the list to the container
menuContainer.appendChild(ul);
}
// Call the function to start fetching the data
fetchMenu();
</script>
</body>
</html>
  1. Initiate Fetch: fetch(menuUrl) starts the network request to the specified URL. It returns a Promise.
  2. Check Response Status: response.ok checks if the HTTP status code indicates success (e.g., 200-299). If not, an error is thrown.
  3. Parse JSON: response.json() reads the response stream to completion and parses the body text as JSON. It also returns a Promise that resolves with the resulting JavaScript object or array.
  4. Process Data: The displayMenu function takes the parsed JavaScript array (menuItems), clears the loading message, and dynamically creates HTML elements (a <ul> list with <li> and <a> elements) to show the menu.
  5. Error Handling: The try...catch block ensures that any errors during the fetch process (network errors, invalid JSON, etc.) are caught and logged, and an error message is shown to the user.

Why fetch instead of XMLHttpRequest?

  • Promise-based: Makes handling asynchronous operations cleaner, especially with async/await.
  • More Flexible: Offers a more powerful and flexible feature set (e.g., easier handling of headers, request/response bodies).
  • Modern Standard: It is the current standard for making network requests in browsers.

For more details on the Fetch API, refer to the MDN Web Docs: Fetch API.