Mental model
A safe JSON fallback separates presentation recovery from data acceptance. When a response ends early or contains invalid JSON, the client keeps the original bytes and may show a bounded repaired preview for inspection; only a complete response that parses strictly, matches its schema, and passes business rules can enter application state or trigger actions.
Learning outcomes
- Distinguish malformed JSON syntax from a syntactically valid object that fails its schema or business rules.
- Calculate the accepted-output rate separately from the rate of repairable previews.
- Design a bounded fallback that preserves the original response and never treats repaired data as trusted input.
Theory
JSON parsing and data validation are separate gates. The JavaScript JSON.parse operation checks whether a string satisfies JSON syntax and produces a JavaScript value; it does not prove that the value has the fields, types, or policy meaning an application requires. A response such as {"title":"Report","items":[]} can parse correctly but still fail a schema that requires at least one item. Conversely, an incomplete stream may contain useful text while remaining invalid JSON.
Completion state matters before either gate runs. A provider can finish because the output limit was reached, return a refusal, fail before producing a response, or complete normally. OpenAI’s Structured Outputs guidance can constrain completed non-refusal output to a supplied schema, but it still calls out refusals, incomplete responses, API errors, and business rules as application responsibilities. Keep the raw payload, request identifier, finish reason, and schema revision so an operator can distinguish a partial response from a completed but malformed one.
A repair library can add a missing quote, comma, or closing bracket and produce a parseable preview. That preview is a hypothesis about what the missing text might have been. With a truncated number, string, or nested value, several valid completions can have different meanings; parser success cannot choose the intended one. Preserve the original response alongside any preview, label the preview as untrusted, and do not feed it into storage, tool execution, billing, or other side effects.
Define as “response completed normally,” as “the original bytes pass strict JSON parsing,” as “the parsed value passes the versioned schema,” and as “business rules pass.” Each predicate is dimensionless and takes value zero or one. Acceptance is the conjunction of all four:
In a batch of 100 attempts, suppose 78 are complete non-refusal responses, 71 of those pass strict JSON parsing, and 68 also satisfy schema and business rules. The accepted-output rate is . A repair preview may make six of the seven malformed complete responses readable, giving a preview rate of , but the accepted-output rate remains 68%. Report those metrics separately so a better-looking preview cannot be mistaken for improved data correctness.
The raw and repaired strings may have different character positions and byte lengths. If the UI points a reviewer to a syntax error, identify which representation and offset unit the location uses. A repair library usually returns a new string rather than a source map, so do not attach original offsets to repaired fields unless you maintain an explicit mapping. The simplest safe review view shows the untouched source and the proposed preview in separate, clearly labeled panes.
Implementation
This example accepts only a complete, non-refusal response that passes strict parsing and Zod validation. The optional jsonrepair result is parsed again, size-bounded, and returned only as an untrusted preview on an incomplete or invalid-JSON display state. Render it as text in a preview pane; never pass it to a tool or persistence layer.
typescriptimport { jsonrepair } from "jsonrepair";import { z } from "zod";const CardSchema = z.object({title: z.string().min(1),items: z.array(z.object({label: z.string().min(1),score: z.number().min(0).max(1),})).max(20),}).strict();type Card = z.infer<typeof CardSchema>;type FinishReason = "complete" | "length" | "error";type Outcome =| { kind: "accepted"; raw: string; value: Card }| { kind: "invalid-json"; raw: string; preview?: unknown }| { kind: "schema-mismatch"; raw: string; fields: string[] }| { kind: "incomplete"; raw: string; preview?: unknown }| { kind: "refused" | "provider-error"; raw: string };function repairPreview(raw: string): unknown | undefined {if (raw.length > 20_000 || new TextEncoder().encode(raw).byteLength > 64_000) return undefined;try {return JSON.parse(jsonrepair(raw));} catch {return undefined;}}export function inspectResponse(raw: string, reason: FinishReason, refused: boolean): Outcome {if (refused) return { kind: "refused", raw };if (reason === "error") return { kind: "provider-error", raw };if (reason === "length") return { kind: "incomplete", raw, preview: repairPreview(raw) };let parsed: unknown;try {parsed = JSON.parse(raw);} catch {return { kind: "invalid-json", raw, preview: repairPreview(raw) };}const result = CardSchema.safeParse(parsed);if (!result.success) {return { kind: "schema-mismatch", raw, fields: result.error.issues.map((issue) => issue.path.join(".")) };}return { kind: "accepted", raw, value: result.data };}const outcome = inspectResponse('{"title":"Report","items":[{"label":"ok","score":0.8}]}', "complete", false);console.assert(outcome.kind === "accepted");
Run repair work in a worker for larger payloads, and cap both the input size and the number of retries. If a completion is truncated and the application elects to retry, use the same request identity for reconciliation, preserve the first raw response, and stop after a small explicit retry budget. A retry can change generated content; it is not a continuation unless the provider’s protocol says so.
Trade-offs
Showing a repaired preview can help a person recover text from a generation that stopped halfway through. It also risks making fabricated closing delimiters look like model-authored content. Keep the raw source visible, label the preview as reconstructed, and require an explicit human action before copying it into an authoritative record. When the output will be consumed by software rather than a person, reject or retry instead of automatically accepting a repair.
Structured output modes reduce syntax and shape errors but may constrain only a subset of JSON Schema and do not establish domain correctness. A score in the range zero to one can still be meaningless for the product. Keep application-specific invariants in code, version the schema, and test representative valid, invalid, refused, and truncated responses. Prefer a single bounded retry when the failure is plausibly recoverable; repeated unconstrained retries can increase cost and duplicate side effects.
Keeping raw data and a preview uses extra memory, especially for long streams. Set a byte limit before invoking a repair pass, store large raw payloads under the product’s retention policy, and avoid logging the full text by default. A compact status record can retain request ID, finish reason, parser state, schema version, and bounded error details without copying sensitive response content into analytics.
Failure modes and misconceptions
- A parseable preview is treated as the model’s original output. Keep and display the original bytes separately from the repaired string.
- Valid JSON is treated as valid application data. Strictly validate the schema, then check domain rules before any side effect.
- An incomplete response is silently repaired and accepted. Preserve its finish reason and keep it in the incomplete state, even if a preview can be constructed.
- A repair changes field meaning. Do not infer missing values or rely on heuristic coercion; make the uncertainty visible and require a new complete response or human review.
- Error positions point into the wrong string. Track offset units and representation; do not reuse offsets after repair without a source map.
- Retry loops multiply work. Bound retry count, keep actions idempotent, and ensure a failed parse cannot trigger the same tool call or write twice.
Decision scenario
An extraction workflow receives a response ending with finish_reason: length. The visible prefix contains a title and two line items, but the last object and array delimiters are missing. A repair preview can display the likely shape, yet it cannot prove the third item’s value or whether the model intended to finish. Preserve the raw response, mark it incomplete, and request one bounded regeneration with a larger output allowance. Do not insert the preview into the invoice database; if regeneration also fails, send the raw and preview views to an authorized reviewer with their status labels intact.