Back to JavaScript Notes
Topic #392

Fetching JSON

You will be able to request JSON data from a server in JavaScript using fetch, wait for the response, check for errors, and convert the body into a JavaScript object.

What it is

Fetching JSON means asking a server for data that is formatted as JSON, then reading that data in your JavaScript code. The fetch function sends an HTTP request and returns a Promise. When the promise resolves, you receive a Response object. The response body is not automatically parsed as JSON; you call response.json(), which also returns a promise that resolves to a JavaScript value.

Related terms include HTTP request, response status, promise, async/await, and JSON parsing.

Why it matters

  • It lets web pages load user profiles, product lists, or settings without reloading the page.
  • It keeps data separate from HTML and JavaScript, making apps easier to maintain.
  • It supports modern asynchronous code with async and await.
  • It gives access to response metadata such as status codes and headers.

Syntax or steps

The smallest useful pattern is:

const response = await fetch("/api/data");
const data = await response.json();

This code must run inside an async function. In real code, also check response.ok and handle errors.

Example

async function loadUser() {
  try {
    const response = await fetch("/api/user");

    if (!response.ok) {
      throw new Error("HTTP error " + response.status);
    }

    const user = await response.json();
    console.log(user.name);
  } catch (error) {
    console.error("Could not load user:", error);
  }
}

loadUser();

Part by part:

  • async function loadUser() creates a function that can use await.
  • await fetch("/api/user") sends a GET request and waits for the server response.
  • response.ok is true only for successful HTTP status codes, usually 200 to 299.
  • response.json() reads the response body and parses JSON into an object.
  • try/catch handles network failures, bad JSON, or thrown HTTP errors.

Common mistakes

  • Forgetting await before fetch or response.json(). Fix it by waiting for both promises.
  • Assuming fetch rejects for 404 or 500 responses. It usually resolves; check response.ok.
  • Not handling invalid JSON. If the server returns HTML or empty text, response.json() throws; use try/catch.
  • Ignoring CORS. If the server does not allow your origin, the request fails; configure server headers or use a same-origin endpoint.

When to use it

Use fetch for most new JavaScript network requests. Use XMLHttpRequest only when you must support very old browsers or need legacy behavior.

NeedUseWhy
Modern browser appfetchClean promise-based API and easy async/await.
Very old browserXMLHttpRequestBroader legacy compatibility.
Simple JSON loadingfetchShort code with response status checks.

Practice

Guided exercise: write an async function that fetches /api/products, checks response.ok, parses JSON, and logs the first product name.

Expected output if the JSON is [{"name":"Keyboard"}]:

Keyboard

Challenge: modify the request to send a query parameter, such as /api/products?category=tools. Hint: build the URL with a template string or string concatenation.

Quick check

Question: Does fetch automatically throw an error when the server returns a 404 status?

Answer: No. It resolves with a response whose ok property is false, so you must check it yourself.

Summary

Fetching JSON is a two-step asynchronous process: request the resource, then parse the response body. Always check the response status and handle errors so your app fails clearly instead of silently.

Want to go beyond the notes?

Join Coding Now Tech Institute's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Fetching JSON – FAQs

Quick answers about learning Fetching JSON in JavaScript.

This free note from Coding Now Tech Institute explains Fetching JSON in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on Coding Now Tech Institute, including Fetching JSON, is 100% free with no signup required.
With focused practice, most students grasp Fetching JSON in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now