How to Fix Broken JSON from ChatGPT & Other LLMs — Free Online Repair Tool

LLMs output invalid JSON constantly — trailing commas, single quotes, unquoted keys, markdown wrappers. This guide covers every error type, the one-click browser fix, and production-grade Python and JavaScript repair code. Nothing uploaded. No signup.

Published June 1, 2026 · 10 min read
Just want to fix it fast? Paste and click Repair →
Auto-fixes trailing commas · single quotes · unquoted keys · 100% browser-based · nothing uploaded
Open JSON Repair Tool →

Why Do ChatGPT and Other LLMs Output Invalid JSON?

LLMs are text prediction engines, not strict parsers. They generate JSON by predicting the most likely next token based on training data — which includes enormous amounts of JavaScript, Python, YAML, and JSON5 in addition to strict JSON. These formats all look similar but have different rules.

JavaScript object literals allow trailing commas and unquoted keys. Python dictionaries use single quotes. YAML and JSON5 allow comments. The model has learned all of these conventions and conflates them, especially when generating longer or more complex JSON structures where attention on earlier formatting rules degrades.

Even with a system prompt that says "return only valid JSON," models slip up. The fix is either preventing the issue at the prompt/API level, or having a reliable repair step before you call JSON.parse().

Fix Broken LLM JSON in 60 Seconds (No Code)

Step-by-step — repair broken JSON
1
Copy the broken JSON from your LLM response
Select the JSON output from ChatGPT, Claude, Gemini, or your API response. Include the full block — with any markdown fences if present.
2
Open the ToolLance JSON Formatter
Go to toollance.com/tools/json-formatter. The tool runs entirely in your browser — your data never leaves your device.
3
Paste into the input box
Paste the broken JSON into the left input pane. The error indicator will immediately show what's wrong and where.
4
Click the Repair button
The Repair button auto-fixes trailing commas, single-quoted strings, and unquoted keys — the three most common LLM JSON mistakes. The fixed JSON appears in the output pane.
5
Validate, then copy or download
Click Validate to confirm the output is now valid JSON. Copy it to clipboard or download as a .json file.

Every Common LLM JSON Error — and How to Fix Each One

Here is a complete breakdown of every JSON error type that LLMs produce, why it happens, and the exact fix — both manually and automatically.

Trailing commasVery common
❌ Broken
{
  "name": "Alice",
  "role": "admin",   ← trailing comma
}
✅ Fixed
{
  "name": "Alice",
  "role": "admin"
}
Why it happens

LLMs are trained on JavaScript codebases where trailing commas are valid (ES5+). JSON does not allow them. The model doesn't distinguish between JS object syntax and JSON.

How to fix

Remove the comma before the closing } or ]. The ToolLance Repair button does this automatically.

Single-quoted stringsCommon
❌ Broken
{
  'name': 'Alice',
  'role': 'admin'
}
✅ Fixed
{
  "name": "Alice",
  "role": "admin"
}
Why it happens

Python and JavaScript both use single quotes extensively. LLMs mix conventions from both languages when generating JSON-like output.

How to fix

Replace all single quotes with double quotes — but only around keys and string values, not inside string content. The Repair tool handles this correctly.

Unquoted keysCommon
❌ Broken
{
  name: "Alice",
  role: "admin"
}
✅ Fixed
{
  "name": "Alice",
  "role": "admin"
}
Why it happens

JavaScript object literals don't require quotes around keys. LLMs trained on JS code frequently drop them when generating JSON.

How to fix

Wrap every key in double quotes. The Repair button matches the pattern word: and converts it to "word":.

Inline commentsOccasional
❌ Broken
{
  "name": "Alice",
  // user role
  "role": "admin"
}
✅ Fixed
{
  "name": "Alice",
  "role": "admin"
}
Why it happens

LLMs add helpful annotations when explaining structured data. Comments are valid in JavaScript and many config formats (YAML, TOML, JSON5) but not in standard JSON.

How to fix

Strip all // line comments and /* */ block comments before parsing. This requires a regex pass — the Repair button handles common cases.

Truncated JSONOccasional
❌ Broken
{
  "users": [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"
  // response cut off here
✅ Fixed
Requires manual completion or re-prompting the model
Why it happens

When a JSON payload is large, the model hits its output token limit mid-response and stops generating. The result is structurally incomplete JSON that no repair tool can fully reconstruct.

How to fix

Re-prompt with "continue from where you left off" or ask for a smaller JSON payload. For automation, increase max_tokens and check for complete closing brackets before parsing.

Markdown code fencesVery common
❌ Broken
```json
{
  "name": "Alice"
}
```
✅ Fixed
{
  "name": "Alice"
}
Why it happens

ChatGPT wraps JSON responses in markdown code blocks by default. JSON.parse() fails because the backticks and 'json' label are not valid JSON.

How to fix

Strip the ```json opening and ``` closing before parsing. In Python: text.strip().removeprefix('```json').removesuffix('```').strip(). In JS: text.replace(/^```json\n/, '').replace(/\n```$/, '').

Fix Broken LLM JSON in Python

For automated pipelines that call LLM APIs and parse the response, you need a robust repair step before json.loads(). These examples range from a simple fence-stripper to a production-grade wrapper with schema validation.

Fix Broken LLM JSON in JavaScript / TypeScript

Whether you're calling the OpenAI API from a Next.js route handler, a browser app, or a Node.js script, you need the same defensive parsing layer. Here are the patterns that cover the most common cases.

Strip markdown fences in JavaScript

Handle the most common case — a ChatGPT response wrapped in ```json ... ``` code fences.

function parseLlmJson(text) {
  // Strip markdown fences
  text = text.trim();
  if (text.startsWith("```")) {
    text = text
      .replace(/^```(json)?\n?/, "")
      .replace(/\n?```$/, "")
      .trim();
  }
  return JSON.parse(text);
}

// Example
const response = `
\`\`\`json
{
  "name": "Alice",
  "role": "admin"
}
\`\`\`
`;

const data = parseLlmJson(response);
console.log(data.name); // "Alice"

Repair common errors with regex

Fix trailing commas, single quotes, unquoted keys, and inline comments before parsing.

function repairLlmJson(text) {
  text = text.trim();

  // Strip markdown fences
  if (text.startsWith("```")) {
    text = text.replace(/^```(json)?\n?/, "").replace(/\n?```$/, "").trim();
  }

  // Remove inline comments (// ...)
  text = text.replace(/\/\/[^\n]*/g, "");

  // Remove block comments (/* ... */)
  text = text.replace(/\/\*[\s\S]*?\*\//g, "");

  // Remove trailing commas before } or ]
  text = text.replace(/,\s*([}\]])/g, "$1");

  // Replace single-quoted keys/values with double-quoted
  // (simplified — handles straightforward cases)
  text = text.replace(/'/g, '"');

  return JSON.parse(text);
}

const broken = `{
  'name': 'Alice',
  role: 'admin',   // unquoted key + trailing comment
  'scores': [95, 87,],
}`;

const data = repairLlmJson(broken);
console.log(data); // { name: 'Alice', role: 'admin', scores: [95, 87] }

How to Prevent Broken JSON Output from LLMs

Repair is the safety net. Prevention is the better strategy for production systems. These three approaches reduce invalid JSON output significantly.

Use structured outputs (OpenAI API)

OpenAI's response_format parameter enforces valid JSON at the API level — the model cannot return invalid JSON.

const response = await openai.chat.completions.create({
  model: "gpt-4o",
  response_format: { type: "json_object" }, // Enforces valid JSON
  messages: [
    {
      role: "system",
      content: "You are a data extractor. Always respond with valid JSON.",
    },
    {
      role: "user",
      content: "Extract name and role from: Alice is an admin.",
    },
  ],
});

const data = JSON.parse(response.choices[0].message.content);

Provide a schema example in the prompt

Showing the model the exact JSON structure you expect dramatically reduces malformed output.

const systemPrompt = `
You are a data extraction assistant.
Always respond with valid JSON matching this exact structure — 
no trailing commas, no comments, double-quoted keys and strings:

{
  "name": "string",
  "role": "string",
  "scores": [number]
}
`;

Validate with a schema (Zod / jsonschema)

Parse first, then validate the structure. This catches cases where the JSON is syntactically valid but semantically wrong.

// Using Zod (TypeScript)
import { z } from "zod";

const UserSchema = z.object({
  name: z.string(),
  role: z.enum(["admin", "user", "viewer"]),
  scores: z.array(z.number()).optional(),
});

function parseLlmUser(text) {
  const raw = JSON.parse(stripFences(text));
  return UserSchema.parse(raw); // Throws if structure is wrong
}

Privacy — Your JSON Never Leaves Your Browser

The ToolLance JSON repair tool runs entirely in your browser using JavaScript. No data is sent to any server. This matters for LLM workflows specifically — your JSON output may contain your system prompt structure, sensitive business logic, user data extracted from documents, or internal API responses. You can verify this by opening your browser's Network tab and confirming no outbound requests fire when you paste and repair.

Related Tools

After repairing, use the JSON Formatter's Tree View to explore nested LLM-generated structures visually — useful for understanding deeply nested AI outputs before parsing them in code. If you're comparing two versions of an LLM's JSON output (a before/after prompt change), the Diff tab highlights exactly what changed between the two responses. Need to get the repaired JSON into a spreadsheet? JSON to CSV Converter converts it in one click — also fully browser-based.

Frequently Asked Questions

Why does ChatGPT output invalid JSON?

LLMs generate JSON by predicting tokens, not by running a parser. They're trained on JavaScript, Python, and YAML in addition to strict JSON — so they mix conventions: trailing commas (valid in JS), single quotes (valid in Python), unquoted keys (valid in JS object literals), and inline comments (valid in JSON5 and YAML). Even with explicit instructions to return valid JSON, models slip up on longer or more complex outputs.

What are the most common JSON errors in LLM output?

The most frequent are: markdown code fences wrapping the JSON (```json ... ```), trailing commas before closing brackets, single-quoted strings instead of double-quoted, and unquoted object keys. Less commonly: inline comments, truncated JSON from hitting the token limit, and escaped characters that don't follow JSON's strict escaping rules.

How do I fix broken JSON online for free?

Paste the broken JSON into toollance.com/tools/json-formatter and click the Repair button. It auto-fixes trailing commas, single quotes, and unquoted keys. Everything runs in your browser — nothing is uploaded.

How do I fix broken JSON in Python?

For production use, install the json-repair library (pip install json-repair) and call repair_json(broken_string) before passing to json.loads(). For simple cases, use regex to strip markdown fences, remove trailing commas, and replace single quotes before parsing.

How do I prevent ChatGPT from returning invalid JSON?

Use OpenAI's response_format: { type: "json_object" } parameter to enforce valid JSON at the API level. In your system prompt, specify "Return only valid JSON with double-quoted keys, no trailing commas, and no comments" and include a schema example. For TypeScript projects, validate with Zod after parsing to catch structurally wrong but syntactically valid responses.

Is my JSON data sent to a server when I use the repair tool?

No. The ToolLance JSON repair tool runs entirely in your browser. Nothing is sent to any server — important when your LLM outputs contain sensitive prompts, business logic, or user data.

Can the repair tool fix truncated JSON?

Partially. The Repair button can fix syntax errors in the content that's present. But if the JSON is structurally incomplete — a response cut off mid-array or mid-object — no tool can reconstruct the missing content. For truncated responses, re-prompt the model with a higher max_tokens limit or ask it to continue from where it left off.