{"record":{"id":"ad0696e8a9114e5c","repo":"langchain-ai/langchain","slug":"invalid-json-output-text","errorCode":null,"errorMessage":"Invalid json output: {text}","messagePattern":"Invalid json output: (.+?)","errorType":"exception","errorClass":"OutputParserException","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/output_parsers/json.py","lineNumber":91,"sourceCode":"        Returns:\n            The parsed JSON object.\n\n        Raises:\n            OutputParserException: If the output is not valid JSON.\n        \"\"\"\n        text = result[0].text\n        text = text.strip()\n        if partial:\n            try:\n                return parse_json_markdown(text)\n            except JSONDecodeError:\n                return None\n        else:\n            try:\n                return parse_json_markdown(text)\n            except JSONDecodeError as e:\n                msg = f\"Invalid json output: {text}\"\n                raise OutputParserException(msg, llm_output=text) from e\n\n    def parse(self, text: str) -> Any:\n        \"\"\"Parse the output of an LLM call to a JSON object.\n\n        Args:\n            text: The output of the LLM call.\n\n        Returns:\n            The parsed JSON object.\n        \"\"\"\n        return self.parse_result([Generation(text=text)])\n\n    def get_format_instructions(self) -> str:\n        \"\"\"Return the format instructions for the JSON output.\n\n        Returns:\n            The format instructions for the JSON output.\n        \"\"\"","sourceCodeStart":73,"sourceCodeEnd":109,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/output_parsers/json.py#L73-L109","documentation":"`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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\nchain = prompt | llm | JsonOutputParser()\n\n// after\nfrom pydantic import BaseModel\nclass Answer(BaseModel):\n    answer: str\n    score: int\nchain = prompt | llm.with_structured_output(Answer)\n// or keep parser but enforce format:\nparser = JsonOutputParser(pydantic_object=Answer)\nprompt = PromptTemplate.from_template(\"{question}\\n{format_instructions}\", partial_variables={\"format_instructions\": parser.get_format_instructions()})","handlingStrategy":"try-catch","validationCode":"import json\n\ndef looks_like_json(text: str) -> bool:\n    t = text.strip()\n    return t.startswith((\"{\", \"[\", \"`\", '\"')) or \"```\" in t\n\n# optional pre-flight; parse_json_markdown still decides\nif not looks_like_json(raw_output):\n    raw_output = reask_for_json(llm, raw_output)","typeGuard":null,"tryCatchPattern":"from langchain_core.exceptions import OutputParserException\n\ntry:\n    data = json_parser.parse_result(result)\nexcept OutputParserException as e:\n    if e.llm_output:\n        repaired = (llm | StrOutputParser()).invoke(\n            f\"Convert this to valid JSON only. Output JSON, nothing else:\\n{e.llm_output}\"\n        )\n        data = json_parser.parse(repaired)\n    else:\n        raise","preventionTips":["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"],"tags":["output-parsers","json","llm-output","structured-output"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}