Fix Invalid JSON from ChatGPT and Other LLMs
Short answer: to fix invalid JSON from ChatGPT, know that most invalid JSON from a language model is a handful of repeat offenders: chat text around the JSON, markdown code fences, single quotes, trailing commas, Python values like None, and output that was cut off. Paste the raw reply into the LLM JSON Guard to extract the JSON, apply the safe repairs, parse it and check it against your schema, with every change listed. Treat anything it marks as a guess as a guess.
Why model output breaks JSON
A model writes text one piece at a time. It has no parser holding it to the JSON grammar, so it often slips in the habits of the text around JSON: a friendly sentence first, a code block, a comment, a Python-style literal. And if the reply hits a length limit it simply stops, possibly in the middle of a string.
The result looks like JSON to a human and fails JSON.parse or json.loads (the classic message is covered in fixing JSON Unexpected token errors). Here is a typical example:
Sure! Here is the data:
```json
{'name': 'Ada', tags: ['a', 'b',], active: True}
```
Let me know if you need anything else.
Six different problems in one reply: chat text, a code fence, single quotes, an unquoted key, a trailing comma and a Python True.
Common problems and what a safe fix looks like
| Problem | Example | Safe fix |
|---|---|---|
| Chat text around the JSON | Sure! Here is… {…} |
Cut everything before the first { or [ and after the matching close |
| Markdown code fences | ```json … ``` |
Remove the fences (choose a block if there are several) |
| Single quotes | {'a': 1} |
Convert to double quotes |
| Curly quotes | “a” |
Replace with straight quotes, only where they delimit strings |
| Unquoted keys | {a: 1} |
Quote the key |
| Trailing comma | [1, 2,] |
Remove it |
| Comments | // note |
Remove outside strings |
| Python literals | None, True, False |
null, true, false, outside strings |
NaN, Infinity |
{"x": NaN} |
Replace with null and warn: the value is lost |
| Cut-off output | {"a": [1, 2 |
Close open strings and brackets and warn: this is a guess |
The first rows are mechanical. There is exactly one correct answer, so a tool can apply them without risk. The last two are different, and that distinction matters.
Safe repairs versus guesses
If an output was cut off, the missing tail is gone. Closing the brackets gives you valid JSON, but not necessarily the data the model meant. Likewise turning NaN into null produces something parseable and silently throws away the original value. Good tooling says so out loud every time, and the LLM JSON Guard does: guessed repairs are marked, and a warning appears.
The related JSON Repair tool follows the same philosophy for ordinary broken JSON. It fixes only what has one unambiguous correction. If a document has more than one plausible fix, for example a missing comma between two unrelated values, it refuses with "No safe deterministic repair available" instead of picking one. Numbers, strings, keys and the order of arrays and objects are copied through exactly.
Valid is not the same as correct
Parsing proves the syntax is right. A JSON Schema goes further and checks the shape: required fields, types, enums, array limits and so on. The LLM JSON Guard validates against a schema you paste and lists every violation with its JSON path (for example $.address.city) and the rule that failed.
Even then, a schema cannot tell you whether a value is true. A model can return a perfectly valid object that contains a wrong date or an invented ID. Validation is the floor, not the ceiling.
How to fix invalid JSON from ChatGPT with the LLM JSON Guard
- Open the LLM JSON Guard.
- Paste the raw model output. Optionally paste a JSON Schema.
- Read the four steps and their results: extract, repair, parse, validate. Each lists the changes it made, and guesses are flagged.
- Fix schema violations at the source if you can, by tightening your prompt or the schema you send to the model.
- Tool-call mode: paste a tool or function definition (the OpenAI, Anthropic or Gemini shape, an object with a
nameand aparametersorinput_schema) and the arguments the model produced. The arguments are cleaned the same way and checked against the definition, and the tool name is compared too. A whole tool call, atool_useblock or arguments copied as a JSON string are unwrapped first. - If your schema is meant for strict structured output, read the strict-schema hints. Several providers want
additionalProperties: falseand every property listed inrequired. Rules differ by provider and change over time, so confirm in the provider's documentation.
If you only need the repair step on a snippet, tick LLM output mode in JSON Repair. It runs the same cleaning scripts, so the cleaned text is identical.
Better than fixing: prevent it
Repair is a safety net. Where your provider offers a structured-output or JSON mode, or constrained decoding against a schema, use it first. Give the model a short example of the exact shape you want, set the output limit high enough that long answers are not cut off (see counting LLM tokens), and always validate before you trust the result.
Limits to know
- A repair cannot recover data that was never written. Cut-off output is repaired by guessing the closing, and the data after the cut is missing.
NaNandInfinitybecomenull, so the original value is lost.- The checker supports the common JSON Schema keywords and tells you about the ones it ignores. It is not a full validator for every draft.
- Text inside strings is never treated as a comment, a Python literal or a quote to fix.
- LLM output mode in JSON Repair accepts up to 2 MB.
- Everything runs in your browser. Nothing is uploaded.
Frequently asked questions
How do I fix invalid JSON from ChatGPT? Paste the reply into the LLM JSON Guard. It strips the chat text and code fences, applies the safe repairs, parses the result and validates it.
Why does the model add "Here is your JSON" before the data? Because it is trained on conversation. Ask for JSON only and use your provider's structured-output option if it has one, then still extract defensively.
Why is the JSON cut off at the end? The reply probably hit the output limit. Raise the limit or ask for a smaller chunk. Do not trust a repaired, truncated object without checking it.
Does a trailing comma break JSON? Yes. Strict JSON (RFC 8259) forbids it, even though many JavaScript parsers do not.
Can a schema guarantee the data is right? No. It guarantees the shape only.
Related tools and guides
- NDJSON and JSON Lines: validate, convert and filter
- Count LLM tokens: estimates, exact counts and JSON cost
- JSON Repair for ordinary broken JSON
- JSON Validator and JSON Formatter (see JSON syntax errors: Unexpected token)
- JSON Schema Validator for checking data against a schema
- AI Output Sanity Check for cut-off code, placeholders, curly quotes and chat text in AI answers
- Token Counter to check how long a prompt or reply is