Parsing and Repairing Streaming LLM JSON Outputs
Recover valid objects from markdown-fenced, trailing-comma, or truncated LLM JSON streams using deterministic state-machine repair before schema validation.
On this page
Why LLM Streams Break Standard JSON Parsers
Even when prompted explicitly to return raw JSON, large language models regularly violate RFC 8259. Models wrap responses in triple-backtick markdown fences (often tagged json or jsonc), prepend polite chatter (“Here is the structured output:”), insert JavaScript-style // comments, emit trailing commas after the last array item, or leak Python literals such as True, False, and None. Worse, when streaming tokens incrementally to a reactive frontend over Server-Sent Events (SSE) or when a generation hits max_tokens mid-response, JSON.parse() throws SyntaxError on every intermediate chunk until the closing brace arrives.
Sending a broken payload back to another LLM call just to fix punctuation wastes latency, doubles token spend, and occasionally hallucinates different values. Solving this reliably requires a deterministic, string-aware lexical pass inside your application runtime. You can test malformed payloads, inspect exact repair diffs, and verify sanitized output interactively in the Interactive JSON Repair Inspector.
Why Regex Replacement Corrupts String Literals
Before writing a repair utility, understand why regex approaches fail subtly in production. Suppose an LLM summarizes a code review inside "comment": "Remove trailing comma before } here,}". A naive regular expression targeting ,} rewrites characters inside the string literal itself, altering your business data without raising an error. Similarly, replacing every single quote ' globally breaks valid English apostrophes like "user's profile", and blindly replacing True everywhere corrupts prose sentences containing the capitalized word "True".
A lexical state machine avoids these collisions by tracking whether the scanner is currently inside a double-quoted string, inside a single-quoted string, inside an escape sequence (\), or outside strings in structural JSON context. Only tokens outside string literals undergo structural repair. Furthermore, because every transformation is recorded in an explicit audit list (changes), your telemetry pipeline can monitor which model prompt needs stricter formatting instructions without guessing.
When integrating with streaming transport layers such as Server-Sent Events (SSE) or NDJSON chunk streams, remember that network buffers split arbitrarily along UTF-8 byte boundaries rather than character or token boundaries. Always decode incoming Uint8Array frames with new TextDecoder("utf-8", { fatal: false }) in stream: true mode before appending text to your repair buffer, otherwise multi-byte emoji or CJK characters spanning two TCP packets turn into replacement characters (\uFFFD). Keeping the transport decoding boundary cleanly separated from lexical repair ensures your parser always evaluates valid Unicode text.
Deterministic State-Machine JSON Repair
The TypeScript function below implements a compact, non-eval state-machine sanitizer that handles four common defects cleanly: markdown code fences, trailing commas before ] or }, single-line/block comments outside strings, and unclosed brackets/quotes on truncated streams. Notice how it never executes eval() or new Function(), keeping untrusted model output strictly inside a data boundary.
export interface RepairResult {
repaired: string;
changes: string[];
parsed: unknown;
}
export function repairLlmJson(raw: string): RepairResult {
const changes: string[] = [];
let input = raw.trim();
// 1. Unwrap triple-backtick markdown fences if present
const fenceMatch = input.match(/^`{3}(?:json|jsonc)?\s*\r?\n([\s\S]*?)(?:\r?\n`{3})?$/i);
if (fenceMatch) {
input = fenceMatch[1].trim();
changes.push("Stripped markdown code fence");
} else {
const firstObj = input.indexOf("{");
const firstArr = input.indexOf("[");
const start =
firstObj === -1 ? firstArr : firstArr === -1 ? firstObj : Math.min(firstObj, firstArr);
if (start > 0) {
input = input.slice(start);
changes.push("Trimmed leading prose before JSON start");
}
}
let out = "";
let inDouble = false;
let inSingle = false;
let escaped = false;
const stack: Array<"}" | "]"> = [];
for (let i = 0; i < input.length; i++) {
const ch = input[i];
const next = input[i + 1] ?? "";
if (inDouble) {
if (escaped) {
out += ch;
escaped = false;
} else if (ch === "\\") {
out += ch;
escaped = true;
} else if (ch === "\n") {
out += "\\n";
changes.push("Escaped literal newline inside string");
} else if (ch === '"') {
out += ch;
inDouble = false;
} else {
out += ch;
}
continue;
}
if (inSingle) {
if (escaped) {
out += ch;
escaped = false;
} else if (ch === "\\") {
out += ch;
escaped = true;
} else if (ch === "'") {
out += '"';
inSingle = false;
} else if (ch === '"') {
out += '\\"';
} else {
out += ch;
}
continue;
}
// Outside any string literal
if (ch === "/" && next === "/") {
while (i < input.length && input[i] !== "\n") i++;
changes.push("Removed line comment");
continue;
}
if (ch === "/" && next === "*") {
i += 2;
while (i < input.length && !(input[i] === "*" && input[i + 1] === "/")) i++;
i++;
changes.push("Removed block comment");
continue;
}
if (ch === '"') {
inDouble = true;
out += ch;
continue;
}
if (ch === "'") {
inSingle = true;
out += '"';
changes.push("Converted single-quoted string");
continue;
}
if (ch === "{") {
stack.push("}");
out += ch;
continue;
}
if (ch === "[") {
stack.push("]");
out += ch;
continue;
}
if (ch === "}" || ch === "]") {
// Drop trailing comma immediately preceding closing delimiter
const trimmed = out.replace(/[ \t\r\n]+$/, "");
if (trimmed.endsWith(",")) {
out = trimmed.slice(0, -1);
changes.push("Removed trailing comma");
}
if (stack.length > 0 && stack[stack.length - 1] === ch) {
stack.pop();
}
out += ch;
continue;
}
out += ch;
}
if (inDouble || inSingle) {
if (escaped) out += "\\";
out += '"';
changes.push("Closed truncated string literal");
}
// Strip dangling trailing comma or colon if stream truncated mid-property
out = out.replace(/,\s*$/, "").replace(/:\s*$/, ": null");
while (stack.length > 0) {
out += stack.pop();
changes.push("Appended missing closing delimiter");
}
const parsed = JSON.parse(out);
return { repaired: out, changes: [...new Set(changes)], parsed };
}
Progressive Streaming Parser vs Final Mutation Boundary
In streaming user interfaces—such as rendering partial tables, summaries, or progress cards as tokens arrive—running repairLlmJson every 80–150 milliseconds allows the UI to render partial typed state smoothly without flickering. Pair the repaired output with a Zod .partial() schema during streaming, then validate against the full strict schema once the stream emits [DONE] or finish_reason === "stop".
import { z } from "zod";
import { repairLlmJson } from "./repair";
const AnalysisResultSchema = z.object({
severity: z.enum(["low", "medium", "high"]),
summary: z.string().min(1),
findings: z.array(z.string()),
});
export function parseStreamChunk(accumulatedText: string, isComplete: boolean) {
const { parsed, changes } = repairLlmJson(accumulatedText);
if (!isComplete) {
// Tolerate missing keys while tokens are still streaming
return {
mode: "preview" as const,
changes,
data: AnalysisResultSchema.partial().safeParse(parsed),
};
}
// Require full schema conformance on final completion
return {
mode: "final" as const,
changes,
data: AnalysisResultSchema.safeParse(parsed),
};
}
Critical Guardrails and Failure Modes
Auto-repairing broken JSON introduces semantic risks if applied without strict guardrails:
- Silent truncation masked as valid JSON: If an LLM hits
max_tokenshalfway through an array of 20 items, closing the brackets produces a syntactically valid 11-item array. Always check the provider’sfinish_reason(stopvslength) before trusting repaired output as complete. - Unquoted object keys and Python literals: Some smaller open-weight models emit
{status: True}without quotes aroundstatus. Extend your token scanner carefully forTrue/False/Noneand bare identifiers only outside quotes, or switch the model to grammar-constrained JSON mode where available. - Dangling key without colon or value: When a stream halts inside
{ "items": [1, 2], "notright after opening a key string, closing the quote leaves,"not"inside an object, whichJSON.parse()rejects because no: valuefollows. Strip trailing unvalued object keys before closing the object brace when handling partial streaming snapshots. - Trailing prose after the closing brace: Assistants frequently add a helpful sign-off paragraph after the JSON payload ends. Make sure your delimiter scanner tracks brace depth down to zero for the root object or array and slices off trailing commentary instead of letting
JSON.parse()reject the extra text. - Latency on huge payloads: Re-parsing a growing 200KB string from byte zero on every single SSE token costs quadratic CPU time. Throttle incremental repair updates to animation frames or every 10–15 tokens rather than running per token.
Verifying Repair Safety and Edge Cases
Before enabling JSON repair in production pipelines, validate edge cases in the Interactive JSON Repair Inspector and cover five assertions in your test suite:
- Strings containing
//,/*,,}, and single quotes remain byte-for-byte untouched after repair. - Truncated mid-stream fragments—ending mid-string, right after a colon
:, or three levels deep in nested arrays—parse into valid objects without throwing. - Trailing prose after the root closing
}(such as"Let me know if you need changes!") does not corrupt the outer delimiter match. - Multibyte UTF-8 characters and unescaped line breaks inside markdown summaries normalize cleanly without splitting surrogate pairs across SSE frames.
- Any invocation where
finish_reason === "length"orchangesincludes closing delimiters is explicitly flagged as incomplete so mutation pipelines refuse to execute partial actions.
FAQ
- Why shouldn't I fix LLM JSON with global regex replacements?
- Regular expressions like text.replace(/,\s*}/g, '}') cannot distinguish syntax punctuation from text inside quoted strings, so they silently corrupt user content containing code snippets, URLs, or natural punctuation.
- Does Structured Outputs eliminate the need for JSON repair?
- Constrained decoding guarantees valid syntax while tokens stay within budget, but network drops, max_tokens truncation, legacy providers, and local open-weight models still produce broken or truncated JSON streams.
- When is it unsafe to repair and execute a truncated LLM JSON response?
- Never execute side-effecting tool calls—such as database writes, payments, or shell commands—from repaired truncated JSON. Use partial repair strictly for progressive UI previews, and demand clean un-repaired completion for mutations.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.