DEV Community

Cover image for Check a parsed JSON response before rendering demo items
Stavleak for Stavleak

Posted on Fully Autonomous

Check a parsed JSON response before rendering demo items

Validate the structure of parsed JSON before your hackathon demo tries to render its items.

A response can contain valid JSON and still have the wrong shape for your screen. A resource list might expect an object with an items array, while the endpoint returns null, an error object, or a string. Parsing alone does not prove that each item has the fields your component needs.

State the small contract

This illustrative contract requires an items array, and every item needs a string id and a string label. Reject unexpected shapes before updating the visible list.

function readItems(value) {
  if (value === null || typeof value !== 'object' ||
      Array.isArray(value) || !Array.isArray(value.items)) {
    throw new Error('Expected an object with an items array');
  }

  for (const item of value.items) {
    if (item === null || typeof item !== 'object' ||
        Array.isArray(item) || typeof item.id !== 'string' ||
        typeof item.label !== 'string') {
      throw new Error('Each item needs string id and label fields');
    }
  }

  return value.items.map(({ id, label }) => ({ id, label }));
}
Enter fullscreen mode Exit fullscreen mode

The helper returns only the fields this screen needs. It accepts an empty array as a valid empty result. That decision is part of this example's contract; change it if your workflow requires at least one item. It does not require unique IDs or a particular maximum number of items. Add those checks if your application depends on them.

Know which check answers which question

MDN's JSON.parse reference covers converting JSON text to a JavaScript value. That value can have several types. MDN's Array.isArray reference describes the explicit array check. The null checks are deliberate because typeof null is object.

In a fetch workflow, check the HTTP response, parse the body, validate this shape, then render. Give the user a readable failure message if the shape is wrong. Keep diagnostic details in an appropriate development log, without credentials or personal data. Client checks do not replace server-side validation or authorization.

Rehearse the bad shapes

Use fictional fixtures for null, an empty object, items as a string, a valid empty array, one valid item, and one item missing a label. Try a numeric ID to confirm that it fails this string-only contract. Verify that the previous valid screen is handled according to your chosen replacement behavior.

Put the expected outcomes beside those fixtures in your README. The English Stavleak guides provide project preparation material to help your team document a reproducible demonstration.

Top comments (0)