Home / Blog / JSON tools

JSON tools

Fetch JSON in JavaScript: Check Status and Validate the Response

Read a JSON response with Fetch, distinguish HTTP and parsing failures, and validate the fields your interface uses before rendering a result.

Check the request, the JSON text and the application shape

Fetching JSON involves more than calling a parser. First obtain an HTTP response, then decide whether its status represents success for the operation, then parse the body and check the fields your application needs. A successful network exchange can contain an error status, and a successful status can contain malformed JSON or an unexpected data shape.

This example expects a same-origin endpoint returning an object with an items array. Each item must have a string identifier and label. Replace the example path with an endpoint you operate or are authorized to use; it is not a live service provided by this article.

async function loadItems(fetcher = fetch, signal) {
  const response = await fetcher("/api/items", {
    headers: { Accept: "application/json" }, signal
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  const payload = await response.json();
  if (!payload || !Array.isArray(payload.items) ||
      !payload.items.every(item =>
        item !== null && typeof item === "object" &&
        typeof item.id === "string" &&
        typeof item.label === "string")) {
    throw new Error("Unexpected items response");
  }
  return payload.items;
}

Handle failures at the boundary where they occur

The Fetch guide explains why an HTTP error response does not automatically reject the Fetch promise. The status check above catches that case before parsing. A network or browser-policy failure can reject earlier, while malformed JSON fails during body parsing. Preserve enough diagnostic context to distinguish these cases without displaying private response contents to every user.

The example deliberately expects a JSON body on success. A 204 response has no content and would need a different contract if the endpoint legitimately uses it. Do not silently convert every empty or invalid body to an empty array, because that makes a server failure indistinguishable from a valid result containing no items.

The Accept header expresses a preference; it does not force an unrelated server to return JSON. A login redirect can end at an HTML sign-in page. Inspect the status, final destination and documented media type when diagnosing an unexpected token error instead of assuming the JSON parser is defective.

Render values according to their intended type

Use text rendering for labels received from the service. Assigning a label to a DOM element's textContent displays it as text, including angle brackets. Inserting the same untrusted string as HTML creates a different security boundary and is unnecessary for an ordinary item label.

Keep loading, empty, successful and failed states distinct in the interface. Clear or deliberately retain old results according to the product design, but label them accurately while a new request is pending. An old list displayed under a newly entered search query can mislead users even if the underlying request eventually succeeds.

When requests can overlap, associate each result with the query that started it. Cancel obsolete requests with an AbortController where appropriate and guard against a stale completion overwriting the current view. Cancellation is a user-interface lifecycle decision, not proof that a server never received a request that was already sent.

Test with controlled responses before using a live endpoint

Injecting fetcher lets a test supply deterministic responses without calling a production service. Check a valid two-item body, an empty items array, an HTTP 500 response, invalid JSON, a missing items property and an item whose identifier is numeric. The expected outcome should identify whether the failure belongs to transport, parsing or application validation.

The JavaScript JSON Parser can inspect pasted response text locally. It does not perform the network request or validate this article's item contract. Use it to isolate a syntax problem, then test the complete request and shape checks in your own application's environment, including any cross-origin and authentication requirements.