Parsing JSON Out of LLM Output: Six Failure Modes and a Layered Fix
Parsing JSON Out of LLM Output: Six Failure Modes and a Layered Fix
You asked for JSON, got back something, and JSON.parse throws. The reflex is to grab a repair library and hope — usually wrong. Classify the failure before you fix it: six of the seven classes below have a deterministic fix, and only one is genuinely a heuristic's job — the one most guides get wrong.
Tip: Automatically detect and fix errors in your JSON using the JSON Fix Tool. Fully client-side and secure—your data never leaves your browser.
Repairing truncated JSON turned a missing value into null
Feed this truncated stream to jsonrepair:
{ "customer": { "name": "Ada", "email": "ada@example.com" }, "orders": [ { "id": 1, "total":It returns, with no error:
{ "customer": {...}, "orders": [ { "id": 1, "total":null}]}The order item survives and the unknown total becomes null. Nothing tells you the value was never received, so downstream code sees a complete-looking order with a null total. That is why the pipeline below detects truncation and fails loudly instead of repairing it.
Constrained Generation Helps — and Doesn't Finish the Job
If your provider offers schema-constrained structured output, tool calling, or function calling, use it. A schema moves the guarantee from "please return JSON" to "this response is decoded against this schema," eliminating most fence, preamble, and quoting mistakes.
Be clear-eyed: it reduces the rate substantially but doesn't eliminate it. Providers can still return an empty response or a refusal, and a stream can still be cut off mid-object by a token limit or a dropped connection.
The Six Failure Modes
1. The Markdown Code Fence
```json
{ "ok": true, "items": [1, 2, 3] }
```Why: models reproduce formatting conventions from training data; "here is JSON" arrives fenced.
Fix: strip it — but not with the regex from the first fence to the next. It breaks the moment a string contains its own backtick fence. Better: scan brace depth and extract the outermost balanced value — one path that also handles preambles and postambles.
2. Prose Preamble and Postamble
Sure! Here's the JSON you requested:
{ "city": "Lisbon", "country": "Portugal" }
Let me know if you'd like me to expand on any of these fields.Why: conversational defaults. Without a strict decoder, the model is answering you, not a parser.
Fix: same answer — extract the outermost balanced value, discard the rest. Prose is not an error condition.
3. Truncated Streaming Output
{ "customer": { "name": "Ada", "email": "ada@example.com" }, "orders": [ { "id": 1, "total":Why: the stream ended. Max tokens, a dropped connection, a timeout.
This is the important one. The instinct is to append the missing } and ]. Repair libraries genuinely will — jsonrepair's documentation lists "add missing closing brackets" and "repair truncated JSON" among its fixes. That is exactly the problem: it succeeds, silently.
You get a syntactically valid object in which the order item survives and the unknown total has become null. No exception. It didn't return a short answer; it returned a wrong answer wearing a valid costume.
A closing brace is a guess about structure, not a recovery of content. The only correct responses are to detect truncation and fail loudly, or to retry.
4. Single Quotes Instead of Double Quotes
{ 'name': 'Bob', 'active': True }Why: Python dominates ML codebases and spells booleans True/False and null as None. Models mirror the distribution.
Fix: safe to handle mechanically. Any decent normaliser rewrites single quotes to double quotes and maps True/False/None onto true/false/null. The mapping is unambiguous, so a heuristic is low-risk.
5. Trailing Comma Before a Closing Brace
{ "a": 1, "b": 2, }Why: JavaScript literals allow trailing commas, so the model treats them as harmless; JSON does not. This is the same dialect mismatch behind the config files that accept comments but reject a trailing comma — see Why JSON Doesn't Allow Comments (JSONC vs JSON5 Explained).
Fix: deterministic — delete the comma. No interpretation is involved.
6. Non-JSON Literals — the Subtle One
{ "score": NaN, "ratio": Infinity, "retries": None }Why: models reach for whatever token is idiomatic nearby. NaN and Infinity are JavaScript Number values, not JSON.
Fix: reject, or map to null yourself. Do not assume a repair library does that: jsonrepair turns NaN and Infinity into the strings "NaN" and "Infinity", a silent type change from number to string. JSON.parse rejects the bare tokens.
const bad = { score: Infinity };
JSON.stringify(bad); // '{"score":null}' — non-finite numbers serialise as null
JSON.parse('{"score":NaN}'); // throwsJSON.stringify writes non-finite numbers as null, so ordinary application code does not produce the bare token. A hand-built string, a Python payload carrying float('nan'), or a library writing raw text still emits the bare token. Normalise at the boundary.
Triage: Match the Response to the Correct Action
| What you actually got | Class | Correct response |
|---|---|---|
| Parses cleanly | valid | Use it as-is. |
| Wrapped in backtick fences | fence | Strip deterministically, or extract by depth. |
| Embedded in chatty prose | prose | Extract the outermost balanced value; discard the rest. |
Single quotes, True/None, unquoted keys |
dialect | Repair or normalise. Unambiguous mapping. |
Trailing comma before } or ] |
syntax | Repair. No interpretation needed. |
| Parses, but the shape is wrong | schema | Validate shape. See Layer 5. |
| Stops mid-object, no closing brace | truncation | Fail loudly, or retry. Never guess. |
Only the last row is unrecoverable without asking the model again.
The Layered Pipeline
// Layers 2-4: extract -> parse -> repair -> re-verify -> detect truncation.
// Layer 2a: scan for the outermost balanced value.
function scan(text) {
let start = -1, depth = 0, inString = false, escaped = false;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (inString) {
if (escaped) escaped = false;
else if (ch === "\\") escaped = true;
else if (ch === '"') inString = false;
continue;
}
if (ch === '"') { inString = true; continue; }
if (ch === "{" || ch === "[") {
if (depth === 0) start = i;
depth++;
} else if (ch === "}" || ch === "]") {
depth--;
if (depth === 0 && start !== -1) {
return { text: text.slice(start, i + 1), complete: true, found: true };
}
if (depth < 0) depth = 0;
}
}
// depth > 0 at EOF: the object never closed.
return start === -1
? { text: "", complete: false, found: false }
: { text: text.slice(start), complete: false, found: true };
}
// Layer 2b: scanning handles fences and prose; the fence regex is the fallback.
function extractJSON(raw) {
const direct = scan(raw.trim());
if (direct.found) return direct;
const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
return fenced ? scan(fenced[1]) : direct;
}
// Layers 3 and 4: strict parse, repair on failure, always re-verify.
function parseLLMOutput(raw, repair) {
const { text, complete, found } = extractJSON(raw);
if (!found) return { ok: false, reason: "no-json-found" };
if (!complete) return { ok: false, reason: "truncated" };
try {
return { ok: true, value: JSON.parse(text), repaired: false };
} catch (err) {
// Strict parse failed -> repair.
}
let repaired;
try {
repaired = repair(text); // e.g. jsonrepair(text)
} catch (err) {
return { ok: false, reason: "repair-threw" };
}
try {
// Re-verify: still-unparseable text is a FAILURE, not a result.
return { ok: true, value: JSON.parse(repaired), repaired: true, original: raw };
} catch (err) {
return { ok: false, reason: "unrepairable" };
}
}The scanner tracks inString and escaped, so a brace inside a double-quoted string is data, not structure. Repair passes deserve the same scepticism: they can return text that still doesn't parse.
The scanner has tested limits:
- Prose such as
See [1] for details: {"a":1}returns[1], because the first balanced bracket pair wins. - A stray quote such as
The 6" model says {"a":1}finds nothing, because the scanner thinks it is inside a string. {'a':'}'}is cut short, because only double-quoted strings are tracked.
Parse failures and shape validation (Layer 5) must catch these.
Layer 5: Validate Shape, Not Just Syntax
Syntactically valid JSON is very often the wrong JSON: an array request returns a single object, a field arrives as "42" when you need 42, a required key is missing. No parser catches this — it's a schema problem.
Derive your types from a known-good sample: capture one good response by hand, then use the JSON → TypeScript converter to generate an interface. A TypeScript interface is erased at compile time and does not validate anything at runtime, so pair it with a runtime validator (a JSON Schema validator or a schema library) that checks every response.
If you also need to author one, the JSON Schema GUI Builder builds a draft-07 schema visually. To be precise about its scope: it is a schema authoring tool — it helps you write one down, it does not validate documents against one.
Repair Is a Heuristic — Know What It Can Silently Change
jsonrepair is capable: per its own documentation it fixes missing quotes, escapes, commas, Python literals, trailing commas, comments, and fences. The JSON Fix Tool works the same way — strict JSON.parse first, and only if that throws does it load jsonrepair, repair, and re-verify. Your text is parsed in the browser and is never uploaded.
Two caveats before putting that on a production path.
It can change meaning. With duplicate keys JSON.parse keeps the last — a fact about JSON itself, not about any repair library. But a repairer choosing between truncated alternatives, or inferring a missing quote inside a string, is making an editorial decision. Never persist repaired output to a system of record without logging the original beside it.
Every layer costs latency and code. On a non-critical path, a single retry with a stricter prompt is often cheaper than a five-layer parser.
FAQ
How do I stop the model wrapping JSON in markdown? Use structured output or tool calling with a schema where available. Otherwise add the extraction layer — a small extraction layer beats repeated prompt iterations.
What do I do when the JSON is truncated mid-object? Detect it and fail loudly: confirm your extracted value reached a closing brace at depth zero. If not, retry or return an explicit error. Never accept a repair pass that closed the brackets — that's a valid object with silently missing fields.
Should I use JSON mode or tool calling? They overlap. JSON mode constrains the output to valid JSON; schema adherence comes from structured output or tool schemas. Tool calling constrains a named argument set and lets one turn carry several calls. Where both exist, tool calling is more expressive — it handles the "no result needed" case. Neither replaces validation.
Why does JSON.parse reject NaN that JSON.stringify produced?
It usually doesn't. JSON.stringify serialises NaN and Infinity as null ({"score":null}), so a round trip is safe. The failure appears when the bare token reaches the parser from elsewhere. Reject or map non-finite numbers at your boundary.
Is it safe to auto-repair and save? For debugging, yes. For a system of record, only with an audit trail: keep the raw response, log which classes were repaired, re-validate the shape before writing. Repair fixes syntax; it can't tell you the document still means what you intended.
Wrapping Up
Parsing JSON out of LLM output is not one problem, it's six — and only one is a heuristic's job. Classify first, extract deterministically, parse strictly, repair only on failure, re-verify always, and log the original whenever a heuristic touched it.
That last habit is the difference between a pipeline that degrades visibly and one that quietly serves wrong data for a year.
🚀 Professional JSON Fixing
The JSON Fix Tool helps you:
- Correct syntax errors automatically
- Validate and repair JSON structure instantly
- Work securely in your browser, with no server uploads
- Copy or export fixed JSON safely