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…
Always verify the format of parsed JSON before attempting to display its items in your demo. A response may have correct JSON formatting but an incorrect structure for your screen. A resource list might anticipate an object containing an items array, while the endpoint could return null, an error object, or a string. Parsing alone does not guarantee that each item includes the fields your component requires.
Define a simple contract This sample contract necessitates an items array, with each item containing a string id and a string label. Reject any deviating shapes before updating the visible list. The function readItems(value) checks for null, non-object type, or an array that is not an array of items. If any of these conditions are met, it throws an error stating, "Expected an object with an items array."
It also verifies each item is an object, not an array, and that the item has string id and label properties. Throw an error with the message, "Each item needs string id and label fields" if any item fails this check. The helper function returns only the fields necessary for the screen. An empty array is considered a valid empty result for this example's contract; modify it if your workflow requires at least one item.
The contract does not mandate unique IDs or a maximum number of items. Add these checks if your application depends on them. Refer to MDN's JSON.parse reference for converting JSON text to a JavaScript value, which can have multiple types. MDN's Array.isArray reference outlines the explicit array check. The null checks are intentional since typeof null is object.
In a fetch workflow, verify the HTTP response, parse the body, validate the shape, and then render. Provide a user-friendly failure message if the shape is incorrect. Store diagnostic details in an appropriate development log, excluding credentials or personal data. Client-side checks are not a substitute for server-side validation or authorization.
Practice handling bad shapes using fictional fixtures for null, an empty object, items as a string, a valid empty array, one valid item, and one item lacking a label. Test the expected outcomes in your README file beside these fixtures. The English Stavleak guides offer project preparation material to assist your team in documenting a reproducible demonstration.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.