Fix "JSONDecodeError: Expecting value" when parsing an LLM response
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- json.decoder.JSONDecodeError: Extra data: line 5 column 1 (char 87)
- json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
- json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 2048 (char 2047)
- pydantic_core._pydantic_core.ValidationError: 1 validation error for Invoice Invalid JSON: expected value at line 1 column 1 [type=json_invalid]
- SyntaxError: Unexpected token '`', "```json ..." is not valid JSON
The text returned by the model is not pure JSON: it starts with a ```json block, a sentence such as “Here is the JSON”, or it is empty or truncated. The real fix is to use the API’s structured outputs (enforced JSON schema at OpenAI, Anthropic, Gemini or Ollama), then validate the result with a Pydantic schema and retry on failure.
What this error means
json.loads() requires text that is exactly valid JSON. “Expecting value: line 1 column 1 (char 0)” means the very first character cannot start a JSON value: an empty string, the backtick of a Markdown block, the first letter of an introductory sentence. An LLM generates text token by token; asking “answer in JSON” in the prompt makes JSON more likely but does not guarantee it. The other variants have specific causes: “Extra data” means text after the object, “Expecting property name” single quotes or a trailing comma, and “Unterminated string” a reply cut off by the max_tokens limit.
Common causes
- JSON wrapped in a Markdown block: the model replies ``
json ...`, which reads well for a human but not forjson.loads`. - Text around the JSON: an introductory sentence, an explanation after the object, or several objects in a row (“Extra data”).
- Empty reply: the content is
Noneor""because the model called a tool, refused, or the code reads the wrong field of the response. - Truncated reply: generation stops at
max_tokens(finish_reason == "length"at OpenAI,stop_reason == "max_tokens"at Anthropic) in the middle of the object. - Almost-JSON syntax: single quotes, trailing commas, comments, Python-style
TrueorNone, common with small local models.
Step-by-step fix
-
Print the raw text and the stop reason
Before fixing anything, look at exactly what
json.loadsreceives withrepr(), and at why generation stopped. If it islengthormax_tokens, raisemax_tokensor ask for a shorter output. Paste the text into a JSON validator to locate the error.# OpenAI Chat Completions choice = response.choices[0] print(repr(choice.message.content)) print(choice.finish_reason) # "length" = truncated # Anthropic Messages print(response.stop_reason) # "max_tokens" = truncated -
Enforce a schema with structured outputs (OpenAI, Anthropic)
Recent APIs constrain generation to a JSON schema: the reply is then always parseable. With the Python SDKs, pass a Pydantic model directly and get the validated object back.
from pydantic import BaseModel class Invoice(BaseModel): number: str total: float currency: str # OpenAI (Responses API) from openai import OpenAI openai_client = OpenAI() response = openai_client.responses.parse( model="gpt-5-mini", input="Extract the invoice: INV-042, 129.90 EUR", text_format=Invoice, ) invoice = response.output_parsed # Anthropic import anthropic claude = anthropic.Anthropic() message = claude.messages.parse( model="claude-opus-5-5", max_tokens=16000, messages=[{"role": "user", "content": "Extract the invoice: INV-042, 129.90 EUR"}], output_format=Invoice, ) invoice = message.parsed_output -
Do the same with Gemini and Ollama
Gemini accepts an
application/jsonMIME type and a schema in its config. Ollama accepts a JSON schema in theformatparameter. Then validate the returned string withmodel_validate_json.# Gemini (google-genai SDK) from google import genai gemini = genai.Client() response = gemini.models.generate_content( model="gemini-2.5-flash", contents="Extract the invoice: INV-042, 129.90 EUR", config={"response_mime_type": "application/json", "response_schema": Invoice}, ) invoice = response.parsed # Ollama import ollama response = ollama.chat( model="llama3.2", messages=[{"role": "user", "content": "Extract the invoice: INV-042, 129.90 EUR"}], format=Invoice.model_json_schema(), ) invoice = Invoice.model_validate_json(response.message.content) -
Extract the JSON robustly when there is no schema
With a model or API without structured outputs, strip the Markdown block, start from the first brace or bracket, and use
raw_decode, which ignores the text after the object. A regex alone is not enough for nested JSON.import json import re def extract_json(text: str): if not text or not text.strip(): raise ValueError("empty model response") fenced = re.search(r"```(?:json)?\s*(.*?)```", text, re.DOTALL) if fenced: text = fenced.group(1) starts = [i for i in (text.find("{"), text.find("[")) if i != -1] if not starts: raise ValueError(f"no JSON found in: {text[:200]!r}") obj, _ = json.JSONDecoder().raw_decode(text[min(starts):]) return obj -
Validate and retry with the error message
Valid JSON can still have the wrong fields: validate it with Pydantic. On failure, send the error back to the model and ask for a corrected version, with a limited number of attempts.
json.JSONDecodeErrorinherits fromValueError, so a singleexceptis enough.from pydantic import ValidationError def ask_invoice(prompt: str, call_llm, attempts: int = 3) -> Invoice: # call_llm(messages) -> str : your API call returning the reply text messages = [{"role": "user", "content": prompt}] for _ in range(attempts): text = call_llm(messages) try: return Invoice.model_validate(extract_json(text)) except (ValueError, ValidationError) as exc: messages += [ {"role": "assistant", "content": text}, {"role": "user", "content": f"Invalid JSON: {exc}. Reply with only the corrected JSON object."}, ] raise RuntimeError("the model did not return valid JSON")
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Use structured outputs whenever the provider offers them, rather than an “answer in JSON” instruction in the prompt.
- Define the expected format once (Pydantic model or Zod schema) and use it both for the request and for validation.
- Always check the stop reason and log the raw reply when parsing fails.
Frequently asked questions
What is the difference between JSON mode and structured outputs?
JSON mode only guarantees syntactically valid JSON. Structured outputs also constrain the reply to a precise schema: required fields, types and allowed values.
Why does the error say “char 0”?
The error happens at the very first character: the reply is empty, or starts with something other than {, [, a quote, a number, true, false or null, typically ``` or a sentence.
Should I use tool calling to get JSON?
It is a valid alternative: with a tool in strict mode, the generated arguments follow its schema. To simply get data back, structured outputs are more direct.
Useful tools for this error
More AI & LLMs errors
- Fix error 429 "Rate limit reached" on OpenAI, Claude and Gemini APIs
- Fix "maximum context length" and "prompt is too long" (context_length_exceeded)
- Fix "CUDA out of memory" in PyTorch
- Fix error 401 "Incorrect API key provided" / "invalid x-api-key"
- Fix "Torch not compiled with CUDA enabled" and torch.cuda.is_available() returning False
- Fix "could not connect to ollama" and connection refused on port 11434
- Fix "You are trying to access a gated repo" (401) on Hugging Face