Skip to content
AI Dev Toolkit.
Esc
  • Loading…

Guide · Developer tools

Why LLMs return invalid JSON, and how to stop it

LLMs return invalid JSON because they generate text token by token and nothing forces it to match JSON syntax. The fix is to turn on your provider’s structured outputs, which constrain the reply to your JSON Schema, then validate every reply with Zod or Pydantic. Repair broken JSON only as a last resort, because a repair can hide missing data.

By Tahir NazirUpdated 13 min read

On this page
  1. Why do LLMs return invalid JSON?
  2. How do you make an LLM return valid JSON?
  3. How does constrained decoding guarantee valid JSON?
  4. How to validate LLM JSON with a schema
  5. What if the JSON is valid but wrong?
  6. What to do when the JSON is cut off
  7. How to retry when validation fails
  8. When should you repair broken JSON?
  9. How to get valid JSON from local models
  10. How to parse streaming partial JSON
  11. Questions people ask

Why do LLMs return invalid JSON?

Because, unless you constrain it, a model writes JSON the way it writes prose: one token at a time, with nothing checking the syntax. It learned from JavaScript, Python and chat transcripts, where single quotes, trailing commas, comments and True are normal, and chat models like to wrap code in Markdown and add a friendly sentence. The common failures:

  • Wrapping: a sentence before the JSON, or a Markdown code fence around it.
  • Loose syntax: single quotes, unquoted keys, trailing commas, comments, Python’s True, False and None.
  • Bad strings: unescaped double quotes or raw line breaks inside a value.
  • Truncation: the reply hits max_tokens and stops mid-value, leaving brackets open.
  • Placeholders: ... in an array where the model shortened a list instead of writing every item.
One reply, five problems. The first four are safe syntax fixes. The fifth isn’t: the repaired JSON parses, but the title stops at “Bernoulli num” because the rest was never generated.

A single one of these makes JSON.parse or json.loads reject the whole reply. The fix is mostly upstream.

How do you make an LLM return valid JSON?

Turn on structured outputs. All three major APIs can constrain the model to a JSON Schema you supply, which is far more reliable than asking for JSON in the prompt. The OpenAI and Anthropic SDKs also accept a Pydantic model (Python) or a Zod schema (TypeScript) and convert it for you; for Gemini you pass the JSON Schema that Pydantic or Zod generates, as in the Gemini example below:

Structured output options, as each provider documents them
ProviderHow to turn it onWatch out for
OpenAItext.format with type: "json_schema" and strict: true (Responses API), or responses.parse with a Pydantic or Zod schemaEvery field must be required and objects need additionalProperties: false. Check for refusal content and status: "incomplete".
Anthropicoutput_config.format with type: "json_schema", or messages.parse; strict: true on tools for tool inputsAdds a system prompt (more input tokens). First use of a schema is slower while its grammar compiles. Check stop_reason for refusal and max_tokens.
Google Geminiresponse_format with mime_type: "application/json" and a schema (responseFormat in JavaScript)Supports a subset of JSON Schema and ignores unsupported keywords. responseSchema is deprecated in the API reference.

From the OpenAI, Anthropic and Gemini structured output docs and API references, checked 2026-10-08.

OpenAI (Python)
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()


class ContactInfo(BaseModel):
    name: str
    email: str
    plan_interest: str
    demo_requested: bool


response = client.responses.parse(
    model="gpt-6-astra",
    input=[
        {"role": "system", "content": "Extract the contact information."},
        {"role": "user", "content": "John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm."},
    ],
    text_format=ContactInfo,
)

contact = response.output_parsed
Claude (Python)
from anthropic import Anthropic
from pydantic import BaseModel


class ContactInfo(BaseModel):
    name: str
    email: str
    plan_interest: str
    demo_requested: bool


client = Anthropic()

response = client.messages.parse(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.",
        }
    ],
    output_format=ContactInfo,
)
print(response.parsed_output)
Gemini (Python)
from google import genai
from pydantic import BaseModel


class ContactInfo(BaseModel):
    name: str
    email: str
    plan_interest: str
    demo_requested: bool


client = genai.Client()

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Extract the contact information: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.",
    config={
        "response_format": {"text": {"mime_type": "application/json", "schema": ContactInfo.model_json_schema()}},
    },
)

contact = ContactInfo.model_validate_json(response.text)

Is JSON mode enough?

No. OpenAI’s older JSON mode (type: "json_object") makes the output parse but doesn’t enforce any schema, and you must still say “JSON” in a message or the API returns an error. OpenAI recommends Structured Outputs instead wherever the model supports it. The main reason to stay on JSON mode is an older model without schema support, and then you have to validate everything yourself.

How does constrained decoding guarantee valid JSON?

By refusing to let the model pick a token that would break your schema. Normally the model can choose any token from its vocabulary at each step. With constrained decoding, the provider turns your JSON Schema into a grammar and, at every step, allows only the tokens that keep the output valid under it: no stray sentence before the brace, no missing quote, no field of the wrong type.

Anthropic describes its version directly: structured outputs work by compiling your JSON Schema into a grammar that constrains Claude’s output, and more complex schemas produce larger grammars that take longer to compile. That compile step is why the first request with a new schema is slower; Anthropic caches compiled grammars for 24 hours from last use. Two limits remain: the grammar can’t stop a reply that runs out of tokens, and it controls the shape of the output, not whether the values are true.

How to validate LLM JSON with a schema

Parse, then validate every reply against a schema, even with structured outputs on. Google’s docs say it plainly: structured output guarantees syntactically correct JSON, not correct values. Anthropic adds that string enum values may come back with different capitalisation. A schema catches both:

validate.ts (Zod 4)
import { z } from "zod";

const Contact = z.object({
  name: z.string(),
  plan: z.enum(["free", "pro", "enterprise"]),
  seats: z.number().int().positive(),
});

const raw = '{"name": "Ada", "plan": "Enterprise", "seats": "5"}';
const result = Contact.safeParse(JSON.parse(raw));
if (!result.success) console.log(z.prettifyError(result.error));

// ✖ Invalid option: expected one of "free"|"pro"|"enterprise"
//   → at plan
// ✖ Invalid input: expected number, received string
//   → at seats
validate.py (Pydantic 2)
from typing import Literal
from pydantic import BaseModel, Field, ValidationError

class Contact(BaseModel):
    name: str
    plan: Literal["free", "pro", "enterprise"]
    seats: int = Field(gt=0)

raw = '{"name": "Ada", "plan": "Enterprise", "seats": "5"}'
try:
    Contact.model_validate_json(raw)
except ValidationError as e:
    print(e)

# 1 validation error for Contact
# plan
#   Input should be 'free', 'pro' or 'enterprise' [type=literal_error, input_value='Enterprise', input_type=str]
#     For further information visit https://errors.pydantic.dev/2.14/v/literal_error

Notice the difference. Zod rejected the string "5"; Pydantic quietly converted it to the number 5, because its default “lax” mode coerces numeric strings. That’s often what you want from a model, but if it isn’t, set model_config = ConfigDict(strict=True): the same input then fails with “Input should be a valid integer”. model_validate_json also reports syntax errors with a position, for example “Invalid JSON: trailing comma at line 1 column 13”, so one call covers both checks.

What if the JSON is valid but wrong?

Then the schema passed and your checks have to go further. Structured outputs and schema validation prove the shape: every required field is present with the right type. They can’t prove the content. A model can return a correctly typed field holding a made-up value, an empty string, a plausible but wrong enum, or a date in the future. Google’s structured output guide says it plainly: syntactically correct JSON isn’t a guarantee that the values are semantically correct.

  • Tighten the schema first. Use enums instead of free strings, minLength for strings that must not be empty, formats for emails and dates, and number ranges. Check which keywords your provider enforces: unsupported ones may be ignored when the model generates, so keep them in your own validator too.
  • Check business rules in code. A total that matches its line items, a start date before the end date, an ID that exists in your database. Zod’s refine and Pydantic’s validators are the place for these.
  • Check against the source. For extraction, confirm that quoted values actually appear in the input text. A value that isn’t in the document is a hallucination, however well formed.
  • Send failures back. Treat a broken business rule like a schema error: return the message to the model for a retry, as in the loop below.

What to do when the JSON is cut off

Check why generation stopped before you parse anything. A reply that ran out of tokens is incomplete, and no repair can bring back what was never written. Structured outputs don’t protect you here: OpenAI and Anthropic both document that a reply cut off by the token limit may not match your schema.

Where each API tells you the reply was cut off
APIField to checkValue meaning “ran out of tokens”
OpenAI Responsesstatus and incomplete_details.reason"incomplete" and "max_output_tokens"
Anthropic Messagesstop_reason"max_tokens"
GeminifinishReason on the candidateMAX_TOKENS

When it happens, retry with a higher output limit, ask for less (fewer items, shorter strings), or split the job into smaller requests. To size the limit, count a typical good reply with the token counter and leave generous headroom: reasoning models also spend output tokens before they write the JSON. Our guide to counting tokens in Python and JavaScript shows how to do it in code.

How to retry when validation fails

Send the error back. A model that sees “Input should be ‘free’, ‘pro’ or ‘enterprise’” usually fixes its next reply, which is cheaper and safer than guessing what it meant. Cap the attempts so a stubborn failure doesn’t loop forever:

retry.py
from typing import Literal
from pydantic import BaseModel, Field, ValidationError

class Contact(BaseModel):
    name: str
    plan: Literal["free", "pro", "enterprise"]
    seats: int = Field(gt=0)

def get_contact(prompt, call_model, max_attempts=3):
    """call_model(messages) -> str is your API call. Retries with the error."""
    messages = [{"role": "user", "content": prompt}]
    for _ in range(max_attempts):
        text = call_model(messages)
        try:
            return Contact.model_validate_json(text)
        except ValidationError as e:
            messages += [
                {"role": "assistant", "content": text},
                {"role": "user", "content": f"That JSON failed validation:\n{e}\nReply with the corrected JSON only."},
            ]
    raise RuntimeError(f"No valid JSON after {max_attempts} attempts")

# Stand-in for a real model: wrong the first time, right the second.
replies = iter(['{"name": "Ada", "plan": "Enterprise", "seats": 5}',
                '{"name": "Ada", "plan": "enterprise", "seats": 5}'])
print(get_contact("Extract the contact.", lambda messages: next(replies)))
# name='Ada' plan='enterprise' seats=5
  • Don’t retry blindly. A refusal or a token-limit stop needs a different fix (a higher limit, a smaller task or a changed prompt), not the same request again.
  • Keep two or three attempts. Each retry resends the conversation, so it costs input tokens again; the LLM cost calculator shows what a retry rate does to a monthly bill, and estimating LLM API costs explains the sums.
  • Log failures. Repeated errors on the same field usually mean the schema or prompt is unclear. Describe the field better instead of retrying harder.
  • Fall back deliberately. After the last attempt, fail loudly or queue the item for a person. Don’t silently store half-valid data.

When should you repair broken JSON?

Repair when you can’t change the request: old models without structured outputs, logs you’re cleaning up, or replies pasted by a person. A repair library fixes syntax well, but it has to guess when the text is ambiguous, and some guesses change your data without an error:

What a repair does with ambiguous input
Model outputAfter repairThe problem
{"total": 12{"total": 12}Was it 12, 125 or 12.50? The number may be cut short.
{"done": tru{"done": "tru"}A cut-off boolean becomes the string “tru”.
{"items": [1, 2, 3, ...]}{"items": [1, 2, 3 ]}The model’s placeholder is dropped, so the list looks complete.
{"msg": "Hello{"msg": "Hello"}The rest of the message is missing, but the JSON looks fine.

Run with jsonrepair 3.15.0, the library our JSON repair tool uses. The tool flags the three cut-off cases as truncated; the dropped ellipsis gets no warning.

So treat repair as a way to see the data, not a way to trust it. Validate the repaired value with your schema, record that it was repaired, and if the reply was truncated, retry instead of keeping the patched version. In Python, the json_repair package does the same job as jsonrepair; for a one-off, our JSON repair tool shows every change it makes. Cleaning up a fine-tuning dataset instead? The fine-tuning JSONL format guide has a validator that checks every line before you upload.

Free toolJSON repairPaste broken JSON or a whole model reply. It fixes the syntax in your browser, shows every change, and warns when the output was cut off.

How to get valid JSON from local models

Use the runner’s grammar or schema option, which applies the same constrained decoding on your own machine. The two most common runners both support it:

  • Ollama: pass a JSON Schema in the format field of the request (for example Contact.model_json_schema() in Python or z.toJSONSchema(Contact) in JavaScript). format: "json" alone only guarantees JSON, with no schema. Ollama’s docs also suggest putting the schema in the prompt as text and lowering the temperature.
  • llama.cpp: its GBNF grammars constrain the output, and it converts a subset of JSON Schema into a grammar for you: send json_schema to llama-server’s completion endpoint, or response_format to its OpenAI-style /chat/completions. Unsupported schema features are skipped silently, so test the schema you use.

llama.cpp notes that the schema only constrains the output and isn’t added to the prompt, so describe the fields in your instructions as well. Small local models obey the grammar but make more value mistakes, so the validation and retry steps above matter even more. Our guide to the differences between Ollama, LM Studio and llama.cpp covers choosing a runner.

How to parse streaming partial JSON

Accumulate the chunks and parse the full text once the stream ends; parse partial text only to preview it. Gemini’s docs say streamed structured output arrives as partial JSON strings that concatenate into the final object, and Anthropic streams tool inputs as input_json_delta events whose partial_json fragments you join and parse when the block stops. OpenAI recommends using its SDK helpers to stream structured outputs.

To show progress before the end, use a parser that accepts incomplete input. Pydantic’s from_json has an allow_partial option, which Anthropic’s streaming docs point to:

partial.py
from pydantic_core import from_json

chunk = '{"name": "Ada Lovelace", "skills": ["maths", "poe'
print(from_json(chunk, allow_partial=True))
print(from_json(chunk, allow_partial="trailing-strings"))

# {'name': 'Ada Lovelace', 'skills': ['maths']}
# {'name': 'Ada Lovelace', 'skills': ['maths', 'poe']}

By default it drops the unfinished string; "trailing-strings" keeps it. In JavaScript, running jsonrepair on the text so far gives a similar preview. Either way, render partial values but don’t act on them: run your schema check and the stop-reason check on the final text before saving anything or calling a tool.

FAQ

Questions people ask

What does invalid JSON mean?

Invalid JSON is text that a strict JSON parser rejects: trailing commas, single quotes, unquoted keys, comments, missing brackets or extra prose around the object. With LLMs the usual causes are Markdown code fences, a sentence before or after the JSON, and replies cut off by the output token limit. Our JSON repair tool shows which of these a reply has.

How do I force ChatGPT or the OpenAI API to return JSON?

Use Structured Outputs: pass a JSON Schema in text.format with strict: true, or pass a Pydantic or Zod schema to the SDK’s responses.parse. The model is then constrained to your schema. Still check status for an incomplete reply and look for a refusal, then validate the parsed result.

What’s the difference between JSON mode and structured outputs?

JSON mode only makes the reply parse as JSON; it can still miss fields or use the wrong types. Structured outputs constrain the reply to a JSON Schema you supply. OpenAI recommends Structured Outputs over JSON mode wherever the model supports it. Either way, a reply cut off by the token limit can still be incomplete.

Do structured outputs guarantee valid JSON?

Almost always, but not in every case. OpenAI and Anthropic both document exceptions: a refusal, or a reply that stops at the token limit, may not match your schema. Anthropic also says string enum values may differ in capitalisation. Check the stop reason and validate every reply with a schema.

Can an LLM return valid JSON that is still wrong?

Yes. Structured outputs guarantee the shape, not the facts: a field can be present and correctly typed but hold a made-up value, an empty string or the wrong enum. Add schema rules such as required fields, enums and formats, then check business rules in code and send failures back to the model for a retry.

How do I get JSON from Claude?

Use Anthropic’s structured outputs: pass a JSON Schema in output_config.format, or a Pydantic model or Zod schema to client.messages.parse, which validates the reply and returns it in parsed_output. For tool inputs, set strict: true on the tool. Check stop_reason for refusal and max_tokens.

Can you fix JSON that was cut off?

You can make it parse by closing the open strings and brackets, which is what repair tools do, but the missing data is gone. A cut-off number or boolean can even turn into a wrong value. The real fix is to retry with a higher output token limit or a smaller request.

Try it

Tools from this guide

Glossary

Key terms in this guide

Keep reading

Keep exploring