langchain-ai/langchain · error · OutputParserException
Invalid json output: {text}
Error message
Invalid json output: {text} What it means
`JsonOutputParser.parse_result` strips the LLM output and hands it to `parse_json_markdown`, which tolerates code fences and surrounding prose but still needs extractable, valid JSON. On `JSONDecodeError` it raises OutputParserException with `llm_output` set to the raw text, chaining the original decode error. In `partial=True` streaming mode the same failure instead returns `None` silently.
Source
Thrown at libs/core/langchain_core/output_parsers/json.py:91
Returns:
The parsed JSON object.
Raises:
OutputParserException: If the output is not valid JSON.
"""
text = result[0].text
text = text.strip()
if partial:
try:
return parse_json_markdown(text)
except JSONDecodeError:
return None
else:
try:
return parse_json_markdown(text)
except JSONDecodeError as e:
msg = f"Invalid json output: {text}"
raise OutputParserException(msg, llm_output=text) from e
def parse(self, text: str) -> Any:
"""Parse the output of an LLM call to a JSON object.
Args:
text: The output of the LLM call.
Returns:
The parsed JSON object.
"""
return self.parse_result([Generation(text=text)])
def get_format_instructions(self) -> str:
"""Return the format instructions for the JSON output.
Returns:
The format instructions for the JSON output.
"""View on GitHub (pinned to e32fa9a52e)
Solutions
- Switch to `llm.with_structured_output(schema)` (tool/function calling or JSON mode) so the model, not a parser, guarantees JSON.
- Improve the parser prompt: include the exact schema (`.get_format_instructions()`), demand 'output ONLY valid JSON', and lower temperature.
- Raise `max_tokens` so long JSON objects are not truncated mid-structure.
- Catch OutputParserException and retry once with the invalid output plus a corrective instruction.
Example fix
// before
chain = prompt | llm | JsonOutputParser()
// after
from pydantic import BaseModel
class Answer(BaseModel):
answer: str
score: int
chain = prompt | llm.with_structured_output(Answer)
// or keep parser but enforce format:
parser = JsonOutputParser(pydantic_object=Answer)
prompt = PromptTemplate.from_template("{question}\n{format_instructions}", partial_variables={"format_instructions": parser.get_format_instructions()}) Defensive patterns
Strategy: try-catch
Validate before calling
import json
def looks_like_json(text: str) -> bool:
t = text.strip()
return t.startswith(("{", "[", "`", '"')) or "```" in t
# optional pre-flight; parse_json_markdown still decides
if not looks_like_json(raw_output):
raw_output = reask_for_json(llm, raw_output) Try / catch
from langchain_core.exceptions import OutputParserException
try:
data = json_parser.parse_result(result)
except OutputParserException as e:
if e.llm_output:
repaired = (llm | StrOutputParser()).invoke(
f"Convert this to valid JSON only. Output JSON, nothing else:\n{e.llm_output}"
)
data = json_parser.parse(repaired)
else:
raise Prevention
- Prefer with_structured_output over text parsing for new code
- Embed get_format_instructions() in the prompt and lower temperature
- Set max_tokens generously for large JSON outputs
When it happens
Trigger: Model emits prose without any JSON, unbalanced braces from truncated output, markdown tables instead of JSON, or code fences containing non-JSON code; long outputs hitting max_tokens mid-JSON in non-partial mode.
Common situations: Prompts that say 'return JSON' without schema enforcement; smaller/cheaper models that ignore format instructions; max_tokens set too low so the JSON is cut off; temperature high enough to break syntax.
Understand the failure class
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
- BooleanOutputParser expected output value to either be {self
- Could not parse function call: {exc}
- Failed to hash metadata: {e}. Please use a dict that can be
- Received unsupported arguments {kwargs}
- with_structured_output is not implemented for this model.
AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14).
Data as JSON: /api/errors/ad0696e8a9114e5c.
Report an issue: GitHub.