A browser has received a response, response.ok is true, and await response.json() has returned. Can the program now display data.workshops[0].title? Only if it has established that the response contains the data this expression requires. JSON parsing establishes a representation rule. The application still needs to establish its own data rules.
This chapter studies the step between parsing and rendering: turning an unknown value into a small, well-defined collection, then replacing the displayed collection coherently. The examples are teaching models, not a description of any real service.
1. Each successful step answers a different question
Suppose an illustrative endpoint, GET /api/workshops, is intended to list workshops and available seats. Consider the following stages:
| Stage | What has been established | What remains to establish |
|---|---|---|
| Fetch fulfills | The call has obtained a response accessible to this script. | Whether its status is the one the endpoint promises. |
| Expected HTTP status | The status matches this endpoint's success contract. | Whether the body has the expected representation and data. |
| JSON parsing fulfills | The body has been read and parsed as JSON. | Whether the resulting value has the required fields and meanings. |
| Application validation succeeds | This value satisfies the checks we explicitly wrote. | Whether the view correctly presents it and whether it is sufficiently current for the reader's purpose. |
| DOM replacement finishes | This script has installed the new displayed collection. | Whether the browser has painted it, or whether server state has changed since the response was produced. |
These conclusions should not be strengthened silently: a status does not establish a schema, and a schema does not establish freshness or permission.
For example, all of the following are valid JSON:
null
["CSS", "DOM"]
{"workshops":"temporarily unavailable"}
None is the workshop collection we are about to define. A parser can accept them correctly while the application rejects them correctly. These are different judgments.
2. Write the contract before writing the property access
Definition 5.2.1
(Response contract)
A response contract is the explicit list of conditions under which a response is accepted: its status, its media type, the shape of the parsed value, the meaning and range of each field, and the relationships between fields and between records. Code reads a property only after the contract has established that it exists and has the expected type.
For this example, the service contract is deliberately small:
- A successful response has status
200and media typeapplication/json, optionally followed by parameters such ascharset=utf-8. - The parsed root is a non-null object, excluding arrays. Its
workshopsfield is an array with at most 50 entries. An empty array means that there are currently no listed workshops. - Each entry is a non-null object, excluding arrays. It has an
id,title,capacity, andseatsRemaining. - An ID consists of one uppercase ASCII letter followed by exactly two decimal digits. IDs must be distinct within the response. This artificial format is an example contract, not a general rule for web identifiers.
- A title is a string. After trimming leading and trailing whitespace, its length is between 1 and 80 JavaScript string code units. This is a code-unit limit, not a count of visible characters.
- Capacity is an integer from 1 through 30. Remaining seats is an integer from 0 through capacity, inclusive.
- Additional fields are allowed but are not copied into the view model.
A valid response might therefore contain:
{
"workshops": [
{"id":"D14","title":" DOM practice ","capacity":12,"seatsRemaining":0},
{"id":"F27","title":"Fetch clinic","capacity":20,"seatsRemaining":7}
],
"generatedFor":"teaching example"
}
The first workshop is full, which is legitimate; rejecting it because !item.seatsRemaining is true would confuse zero with absence. Likewise "7" is a string even though it looks numeric, so the client rejects it instead of silently repairing the service's response.
The inequality seatsRemaining <= capacity is a relationship between fields: capacity 8 with 11 remaining seats passes each integer check yet contradicts the meaning of remaining capacity. Uniqueness is a relationship between records: two entries can each be well formed while a repeated ID makes the collection ambiguous for later selection, keyed rows or update requests. Validation must therefore inspect the collection as well as its entries.
Common mistake
(Measuring the title before trimming)
Checking item.title.length on the raw string, and only afterwards trimming for display, answers the wrong question. The string " " has length 3, so a test such as item.title.length > 0 accepts it, yet after trimming it is empty and the list would show a blank row. In the other direction, a title of 80 visible code units with one leading space has raw length 81 and would be wrongly rejected by a raw bound of 80. Trim first, then test the length of the trimmed string, as decodeWorkshops does.
3. Decode once, returning only the data the page uses
The following function is synchronous. Its input is the value returned by JSON parsing, not the JSON text. It either throws an error or returns a new array of new records with the stated fields.
function isRecord(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function decodeWorkshops(value) {
if (!isRecord(value) || !Array.isArray(value.workshops) ||
value.workshops.length > 50) {
throw new Error("Expected a workshop collection with at most 50 entries");
}
const seenIds = new Set();
return value.workshops.map((item, index) => {
if (!isRecord(item)) {
throw new Error(`Workshop ${index + 1} is not a record`);
}
if (typeof item.id !== "string" || item.id.length !== 3 ||
!/^[A-Z][0-9]{2}$/.test(item.id)) {
throw new Error(`Workshop ${index + 1} has an invalid ID`);
}
if (seenIds.has(item.id)) {
throw new Error(`Workshop ${index + 1} repeats an ID`);
}
if (typeof item.title !== "string") {
throw new Error(`Workshop ${index + 1} has no text title`);
}
const title = item.title.trim();
if (title.length === 0 || title.length > 80) {
throw new Error(`Workshop ${index + 1} has an invalid title length`);
}
if (!Number.isInteger(item.capacity) || item.capacity < 1 || item.capacity > 30 ||
!Number.isInteger(item.seatsRemaining) || item.seatsRemaining < 0 ||
item.seatsRemaining > item.capacity) {
throw new Error(`Workshop ${index + 1} has inconsistent seat counts`);
}
seenIds.add(item.id);
return {
id: item.id,
title,
capacity: item.capacity,
seatsRemaining: item.seatsRemaining
};
});
}
The name isRecord describes only the limited shape test used here. The decoder expects the unmodified output of JSON parsing in an ordinary browser, not arbitrary objects with getters, proxies or changed prototypes.
The order of checks matters: confirm item is non-null before reading its fields and title is a string before calling .trim(). typeof null is "object" and arrays are objects too, so the helper excludes both explicitly.
If the third item fails, .map() throws before returning an array, so nothing reaches the renderer: invalid input never produces a partly accepted list. This does not roll back anything on the server.
Worked example 5.2.2
(Classify the earliest failed assumption)
Treat each row as an independent call on fresh input. For the abbreviated entry cases, assume the other fields are valid and the root is { "workshops": [entry] }.
| Input or changed field | Decoder result | Reason |
|---|---|---|
Root null | Throws at the root check. | No object field access is justified. |
Root { "workshops": [] } | Returns []. | An empty collection is valid under the contract. |
Root { "workshops": {} } | Throws at the root check. | An object is not an array. |
seatsRemaining: 0, capacity: 12 | Accepts the entry. | Zero is an integer in the permitted interval. |
seatsRemaining: "0", capacity: 12 | Throws at the seat check. | Integer validation does not coerce strings. |
seatsRemaining: 13, capacity: 12 | Throws at the seat check. | The cross-field inequality fails. |
title: " " | Throws at the title-length check. | Trimming leaves no title. |
Two otherwise valid entries both use D14 | Throws on the second entry. | The collection violates ID uniqueness. |
For the two-entry valid response above, the decoder returns the title "DOM practice" for D14 and keeps its zero remaining seats. The page can then derive capacity - seatsRemaining: 12 occupied seats for D14 and 13 for F27. With at most 50 workshops and capacity at most 30, these differences stay far inside the exact integer range of JavaScript numbers.
Counterexample mode
typeof number is not a seat count
Claim: typeof item.capacity === "number" && typeof item.seatsRemaining === "number" && item.seatsRemaining <= item.capacity validates the seat counts. Take the parsed values capacity: 12.5 and seatsRemaining: 3.25. Both are numbers and 3.25 <= 12.5, so the weak check accepts them, and the page prints "3.25 of 12.5 seats available" with capacity - seatsRemaining equal to 9.25 occupied seats, which is not a count of seats. Even the literal 1e400 is valid JSON, and JSON.parse turns it into Infinity, which is also of type "number"; with seatsRemaining: 5 the weak check passes and the occupied count is Infinity. The contract requires an integer from 1 through 30 for capacity and an integer from 0 through capacity for remaining seats. Number.isInteger rejects both 12.5 and Infinity, and the range tests then enforce the stated limits.
4. Separate preparing a view from replacing the displayed view
A tempting renderer clears the list, then validates and appends entries one at a time. If entry three fails, two rows are visible, the old list is gone, and the reader cannot tell whether only two workshops exist or loading broke halfway.
For this small response, validate the complete value first, then construct all replacement rows in a detached DocumentFragment. Only after that preparation succeeds should the program replace the list's children.
function prepareWorkshopList(workshops) {
const fragment = document.createDocumentFragment();
if (workshops.length === 0) {
const row = document.createElement("li");
row.textContent = "No workshops are currently listed.";
fragment.append(row);
return fragment;
}
for (const workshop of workshops) {
const row = document.createElement("li");
const title = document.createElement("strong");
title.textContent = workshop.title;
const seats = document.createElement("span");
seats.textContent =
` — ${workshop.seatsRemaining} of ${workshop.capacity} seats available`;
row.dataset.workshopId = workshop.id;
row.append(title, seats);
fragment.append(row);
}
return fragment;
}
The program creates the structure and each title becomes text: a title such as "<em>DOM</em>" stays literal characters and creates no element. Using textContent avoids interpreting that text as HTML in this operation; it says nothing about later use of the value as a URL or CSS.
After preparation, list.replaceChildren(fragment) swaps the old children for the fragment's children, and the fragment itself ends up empty. This reduces the partial-list problem at application level without making all DOM operations transactional.
5. Connect the stages without inventing a server
Place the following markup in a page. The script is assumed to run after this markup, once. The previous two function definitions must be available before the listener is registered.
<button id="reload-workshops" type="button">Reload workshops</button>
<p id="workshop-status" role="status">No list has been loaded.</p>
<ul id="workshop-list"></ul>
const reloadButton = document.querySelector("#reload-workshops");
const status = document.querySelector("#workshop-status");
const list = document.querySelector("#workshop-list");
async function readWorkshops(response) {
if (response.status !== 200) {
throw new Error("Unexpected workshop response status");
}
const mediaType = (response.headers.get("Content-Type") ?? "")
.split(";")[0].trim().toLowerCase();
if (mediaType !== "application/json") {
throw new Error("Expected a JSON media type");
}
const value = await response.json();
return decodeWorkshops(value);
}
reloadButton.addEventListener("click", async () => {
reloadButton.disabled = true;
status.textContent = "Loading; any displayed list is from an earlier load.";
try {
const response = await fetch("/api/workshops", {
headers: { Accept: "application/json" }
});
const workshops = await readWorkshops(response);
const fragment = prepareWorkshopList(workshops);
list.replaceChildren(fragment);
status.textContent = `Loaded ${workshops.length} workshops.`;
} catch {
status.textContent =
"Could not load a usable list. Any displayed list is from an earlier load.";
} finally {
reloadButton.disabled = false;
}
});
The endpoint is an assumption of this example. The Accept header states a preference; it cannot force valid JSON. We check the declared Content-Type under our strict contract, and parsing then checks the actual syntax, so a text/plain response containing valid JSON is deliberately rejected.
We require exactly 200 instead of response.ok because this contract promises that status and a body. A 204 is a successful status but carries no workshop representation, and empty content is not the same as { "workshops": [] }, which is an explicit empty collection. This is an endpoint-specific decision.
The button is disabled while a load is pending, so this program handles one load at a time. That is not general race control: if other code could start loads, a request sequence number could stop an older response from replacing a newer one.
Note the failure policy. The old list remains while loading and after any failed response, parsing or validation step, and the status says it is from an earlier load; labeling it current would mislead. A successful empty collection replaces the rows with the empty-list message. A failure and an empty success must not look the same.
Worked example 5.2.3
(Four responses through readWorkshops)
Each row is a separate call of readWorkshops; the click handler then decides what the screen shows.
| Response | Path through the loader | Screen result |
|---|---|---|
200, application/json; charset=utf-8, body {"workshops":[]} | Status and media type pass, parsing succeeds, the decoder returns [] | The empty-list message replaces the old rows; status Loaded 0 workshops. |
200, text/html error page | The media-type check throws before the body is read | Old rows stay; status says no usable list |
204, no body | The status check throws | Old rows stay; status says no usable list |
200, application/json, body {"workshops":"temporarily unavailable"} | Parsing succeeds; the decoder's root check throws | Old rows stay; status says no usable list |
Only the first row changes the displayed collection. The other three leave the earlier rows in place because each fails a different stage: status, media type, decoded shape. Reading them in order shows why the stages are separate: the HTML page never reaches response.json(), while the fourth body is perfectly good JSON that is still not a workshop collection.
Worked example 5.2.4
(The second reload has a broken record)
Assume the first load has completed successfully with D14 and F27.
- The reader clicks reload. The button becomes disabled. The two old rows remain, and the status explains that they come from an earlier load.
- Fetch obtains a
200 application/jsonresponse. Itsworkshopsarray contains three records. - JSON parsing succeeds. The first two records satisfy the decoder, but the third has
capacity: 6andseatsRemaining: 9. - The decoder throws.
readWorkshopstherefore rejects, so control leaves the awaited call and enterscatch. NeitherprepareWorkshopListnorreplaceChildrenis reached. - The old rows are still
D14andF27. The status says that a usable list could not be loaded, andfinallyenables another attempt.
The result is not “the server listed two workshops.” It is “this page still displays a previous successful result because the replacement result failed the stated contract.” That is the evidence the interface should communicate.
Now change only the second response to { "workshops": [] }. Validation returns an empty array, preparation creates the empty-list message, and replacement removes both old workshop rows. The status reads Loaded 0 workshops. No failure has occurred.
6. Read a response body once under one chosen interpretation
The body is consumed when it is read. This diagnostic sequence is therefore wrong for an ordinary response:
const debugText = await response.text();
const data = await response.json(); // the same body has already been consumed
The second call normally rejects because the body has already been used. Choose the reading strategy in advance; if text is needed first, read it once and call JSON.parse on that string, then validate. That moves where parsing errors occur but does not remove the need to validate.
7. What the validator has proved, and what it has not
On success decodeWorkshops guarantees the stated title, identity and seat-count properties, which supports predictable display and bounded arithmetic. It does not prove that the server's seat counts are truthful or still current, or that a reader may reserve a seat; a reservation request must be validated and authorized by the server, which enforces capacity. A client-side count is information, not a lock.
For study, trace the four representations in order: response, parsed value, validated collection, prepared DOM. At each arrow, name the assumption being checked and the behavior on failure. This gives property accesses, arithmetic and visible updates a reason to be correct, rather than relying on the happy-path shape of a single sample response.
Practice
Quick check
(Root shape)
The parsed value is the JSON array [{ "id": "D14", "title": "DOM practice", "capacity": 12, "seatsRemaining": 0 }]. Does decodeWorkshops accept it? Which check decides, and why is no property read before that check?
Solution
It throws. isRecord excludes arrays, so !isRecord(value) is true and the function throws before value.workshops is evaluated. The contract needs an object root holding a workshops array; an array root is valid JSON but not this collection.
Quick check
(The zero trap)
A colleague writes if (!item.seatsRemaining) throw new Error("missing seats");. Give two inputs that this line treats wrongly, and replace it with the contract's check.
Solution
0 is falsy, so a full workshop with seatsRemaining: 0 is rejected although the contract allows it. The string "7" is truthy, so it passes although the contract requires a number. The correct check is Number.isInteger(item.seatsRemaining) && item.seatsRemaining >= 0 && item.seatsRemaining <= item.capacity, applied after capacity itself has been validated.
Quick check
(Right body, wrong label)
The server answers 200 with Content-Type: text/plain and the body {"workshops":[]}. What does the page show, and is the previous list kept?
Solution
readWorkshops throws at the media-type check, so response.json() is never called. The click handler's catch sets the status to the failure message and the earlier rows remain, labeled as coming from an earlier load. The body would have been a valid empty collection, but this contract also requires the declared media type application/json.
Quick check
(Markup in a title)
An entry has the title "<b>Hi</b>". Does the decoder accept it, and what does the reader see in the list?
Solution
The decoder accepts it: it is a string whose trimmed length is 9, within 1 to 80. Validation checks shape and range, not markup. prepareWorkshopList assigns it to textContent, so the reader sees the literal characters <b>Hi</b> and no bold element is created. Shape validation and output handling answer different questions.
Quick check
(A repeated ID)
Two otherwise valid entries both have the ID D14. Which check fails, on which entry, and what reaches the renderer?
Solution
The first entry passes and its ID is added to seenIds. On the second entry seenIds.has(item.id) is true, so the decoder throws "Workshop 2 repeats an ID". Nothing reaches the renderer, the click handler's catch runs and the old rows stay. Uniqueness is a relationship between records, so only a check that remembers earlier entries can detect it.