Skip to content
Debugging

How to Fix Invalid JSON Generated by AI (Without Breaking the Data)

·5 min read
How to Fix Invalid JSON Generated by AI (Without Breaking the Data) - Debugging guide from JSON Prettifier

Quick answer: Most "invalid" AI-generated JSON is valid JSON surrounded by things that are not JSON: a Markdown code fence, an explanatory sentence, or a stray trailing comma. Isolate the text between the outermost braces, run it through a validator, and fix only the syntax error it reports. If the output stops mid-structure, request it again rather than guessing at the missing data.

You ask an AI assistant for JSON. It gives you something that looks like JSON. You paste it into your application—and JSON.parse() throws an error.

The important distinction is simple: an AI response can contain JSON-looking text without being a valid JSON document. Markdown, extra commentary, missing characters, and even valid but unexpected data shapes can all cause trouble.

Here's how to find the real issue without replacing random characters and accidentally changing a value.

Repair a copy of the failing payload with the JSON Fixer, then review the changes before using the result.

1. First, separate JSON from the surrounding answer

An assistant may respond like this:

Here is your data:

```json
{"name":"Maya","active":true}
```

That is a useful chat answer. It is not valid JSON as a whole. The explanation and triple-backtick code fence are not part of JSON syntax. Feed the whole thing to a parser and you get an Unexpected token error at position 0, because H from "Here" is not a valid start of a JSON document.

If a person is copying it, select only:

{"name":"Maya","active":true}

If you're processing model output in code, prefer a provider's supported structured-output or schema-constrained mode where available. Avoid building a fragile parser that assumes the response will always be wrapped in Markdown.

2. Remove trailing commas, not every comma

This is invalid JSON:

{
  "customer": "Maya",
  "items": ["book", "pen",],
}

The commas immediately before ] and } are the problem. A valid version is:

{
  "customer": "Maya",
  "items": ["book", "pen"]
}

Don't delete commas with a global regular expression. A comma inside a text value—"Ahmedabad, Gujarat"—is perfectly legal and should stay there. Models produce this mistake often because trailing commas are allowed in JavaScript object literals; the trailing comma guide covers how to find them in long documents.

3. Check double quotes and escaped characters

JSON keys and strings require double quotes. JavaScript-like output is not always JSON:

{ name: 'Maya', active: true }

Here is the actual JSON equivalent:

{"name":"Maya","active":true}

A different problem appears in Windows paths or quoted messages. This string is invalid because \U is not a supported JSON escape sequence:

{"path":"C:\Users\maya"}

JSON recognizes only \", \\, \/, \b, \f, \n, \r, \t, and \uXXXX. The raw JSON needs doubled backslashes to represent literal backslashes:

{"path":"C:\\Users\\maya"}

Do not transform values blindly. An incorrectly escaped path may parse while pointing somewhere completely different. The full list of rules is in the JSON escape characters guide.

4. Watch for incomplete output

Long AI responses sometimes stop halfway through an array or object because the generation ended before the document was complete. For example:

{"products":[{"id":1},{"id":2}

It's tempting to add ]} and call it fixed. But you don't know whether more products were supposed to be present. In production, treat truncated JSON as a generation or transport failure. Request a complete response, validate it, and retry under a defined policy rather than inventing missing business data.

5. Syntax and structure are different checks

This is perfectly valid JSON:

{"price":"49.99","quantity":"three"}

But it may be useless to your application if price must be a number and quantity an integer.

A syntax validator answers Can this be parsed? A JSON Schema or application validator answers Does this data match the contract? You need both for reliable AI-driven workflows.

For example, in JavaScript:

function parseModelJson(text) {
  try {
    return { ok: true, value: JSON.parse(text) };
  } catch (error) {
    return { ok: false, error: error.message };
  }
}

This only checks syntax. Your next step should validate required properties and types before saving a record, executing a command, or sending it to another service.

6. The quickest manual debugging process

  1. Copy the raw response as received by your code, not a prettier-looking screenshot.
  2. Paste the candidate JSON into JSON Prettifier and validate it.
  3. Read the reported error position and inspect the nearby characters.
  4. Remove only verified syntax mistakes; do not guess at missing business values.
  5. Validate the result against the expected data structure or schema.
  6. Add an automated regression test for the failure so it stays fixed.

Keep secrets out of online debugging tools unless you have confirmed how the tool processes data and your organization's policy permits it. You can also reproduce errors with harmless test data, or redact the sensitive fields before pasting.

How to reduce the problem next time

Ask for a well-defined shape with exact field names and types, supply a small valid example, and use structured-output features where supported. Still handle errors in code: malformed output, refusals, transport interruptions, and schema-level mistakes are all possible operational cases.

Related: JSON parse errors, common JSON syntax mistakes, and JSON security best practices.

Bottom line

The fastest reliable fix isn't a trick that turns every AI answer into JSON. It's a process: isolate the payload, validate the syntax, verify its shape, and retry when the intended data is unknowable.

If your response fails only while it is arriving, use the guide to streaming JSON from AI APIs to separate unfinished fragments from a completed payload.

Before promoting a recovered candidate into application processing, apply these four JSON repair acceptance checks for source selection, completeness, application invariants, and review evidence.

Frequently Asked Questions

Can I automatically repair any invalid AI-generated JSON?
Not safely. Obvious syntax slips such as a trailing comma or a Markdown code fence can be stripped mechanically, but missing or contradictory values need a fresh response or a human decision.
Why does the AI wrap its JSON in a Markdown code fence?
Chat models format answers as Markdown, and a fenced block is how Markdown marks code. The fence and any explanatory text are not part of JSON, so extract only the text between the outermost braces or brackets before parsing.
Will formatting fix broken JSON?
No. A formatter only re-indents JSON that already parses. When the input is invalid, a validator reports the position of the first error so you can fix it by hand; it should never invent missing data.
What should I do when the AI response is cut off in the middle of the JSON?
Treat it as a failed generation. Request the output again, or raise the response length limit, instead of closing the brackets yourself, because you cannot know what data was supposed to follow.
Is valid JSON enough for production AI features?
No. Check syntax first, then validate the shape against a JSON Schema or your application rules, and apply the same authorization and data-sensitivity checks you would for any user-supplied input.

Validate the payload before you touch it

Paste the JSON the model returned into JSON Prettifier. It reports where the first syntax error is, and formats valid output so you can read the structure before your code depends on it.

Open JSON Prettifier