Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

Check a Parsed JSON Response Before Rendering Demo Items

A parsed JSON response can still have the wrong shape. Validate the fields your demo-item UI expects before passing data to its renderer.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Parse the response, check that it matches the shape your demo-item component expects, and render only the checked data. JSON parsing catches malformed JSON; it does not guarantee that a valid JSON value contains the right fields or types. Keep parsing, validation and rendering as separate steps so an unexpected response cannot flow straight into the UI.

Why parsing is not enough

A JSON parser can turn a response body into a JavaScript value: an object, array, string, number, boolean or null. It cannot tell whether that value satisfies your app’s contract. For example, {"items":[{"id":7,"name":null}]} is valid JSON, but it may not be suitable for a component that expects each item to have a string ID and a string name.

Define the contract from what the renderer actually uses. For a demo list, that might mean an object with an items array, where every item has a string id and name. Add other fields only if the UI needs them, and decide whether extra fields are allowed. Redux Toolkit Query documents runtime response validation through an endpoint’s responseSchema; the schema still needs to describe your endpoint’s actual response (Redux Toolkit Query: Queries).

Validate ordinary item data before rendering

The following browser JavaScript example uses a small explicit validator, so it does not require a validation-library dependency. It accepts only an object with an items array whose entries have string id and name fields. Adjust the contract to match your API and component rather than copying these example fields blindly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function isDemoItemsResponse(value) {
  return isRecord(value)
    && Array.isArray(value.items)
    && value.items.every(item =>
      isRecord(item)
      && typeof item.id === "string"
      && typeof item.name === "string"
    );
}

async function loadDemoItems() {
  try {
    const response = await fetch("/api/demo-items");
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }

    let parsed;
    try {
      parsed = await response.json();
    } catch {
      throw new Error("The response body is not valid JSON.");
    }

    if (!isDemoItemsResponse(parsed)) {
      throw new Error("The response does not match the demo-items contract.");
    }

    renderDemoItems(parsed.items);
  } catch (error) {
    showDemoItemsError(error.message);
  }
}

Here, the API path, item fields, renderer and error function are illustrative; replace them with your project’s real endpoint and UI functions. The important boundary is the call to isDemoItemsResponse: renderDemoItems receives parsed.items only after the check passes. For complex or evolving payloads, a runtime schema library can express the contract more maintainably than hand-written checks.

Keep failure cases distinct

Handle transport or HTTP failures, JSON parse failures, and schema failures deliberately. A server can return an error status, a body that is not JSON, valid JSON of the wrong shape, or valid data. Those cases may deserve different diagnostics, but none should fall through to rendering unchecked values.

  • Request failure: the fetch fails or the HTTP status is not successful; show the relevant loading/error state.
  • Parse failure: the body cannot be decoded as JSON; report that separately from a shape mismatch.
  • Validation failure: JSON parsing succeeds, but the result violates the UI contract; do not pass it to the item renderer.
  • Success: pass the validated data to the renderer and leave the error state.

In a larger app, return structured validation errors rather than a single generic message if that helps logging or debugging. Avoid displaying raw server payloads as UI content simply because they parsed successfully.

Choose the validation boundary that fits the data

Ordinary API records

For item records fetched from an endpoint, validate as close to the data-fetching boundary as practical. If the app already uses Redux Toolkit Query, its responseSchema option is documented for runtime validation during the endpoint lifecycle (Redux Toolkit Query: Queries). Confirm that the schema matches the endpoint’s real response and the installed project setup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Data that describes a UI

A generated UI specification is not just an array of records. It can determine which components are created and how they are arranged, so constrain both the allowed structure and component properties. json-render describes validating specifications against a predefined catalog before rendering them (json-render: Specs; json-render: Core API). Its documentation shows a schema/catalog validation flow and React rendering through a renderer and registry. That pattern is relevant to UI specifications, not automatically necessary for a simple list of API items.

Structured model output

If the API response comes from a model using structured output, still check that the result matches the schema and parse it into native data before relying on it in the UI. Structured output narrows the format the producer is asked to return; the component should still receive data that satisfies its own rendering contract.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What to verify in your app

  • Write down the exact object, array and field types your renderer consumes.
  • Decide explicitly whether missing fields, null values and additional properties are valid.
  • Validate nested objects and optional values too if the component accesses them.
  • Test malformed JSON and valid JSON with the wrong shape, not only the expected success response.
  • Ensure every failure path preserves a safe empty, loading or error state instead of attempting to render unchecked data.

There is no universally preferred validator for an unspecified app. The right choice depends on its stack, whether validation belongs in the endpoint lifecycle, and whether the payload is ordinary records or a specification that controls UI structure.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.