{"record":{"id":"766980eaf6f53562","repo":"run-llama/llama_index","slug":"failed-to-convert-output-to-json-output-r","errorCode":null,"errorMessage":"Failed to convert output to JSON: {output!r}","messagePattern":"Failed to convert output to JSON: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"llama-index-core/llama_index/core/output_parsers/selection.py","lineNumber":97,"sourceCode":"\n                # NOTE: parsing again with pyyaml\n                #       pyyaml is less strict, and allows for trailing commas\n                #       right now we rely on this since guidance program generates\n                #       trailing commas\n                json_obj = yaml.safe_load(json_string)\n            except yaml.YAMLError as e_yaml:\n                raise OutputParserException(\n                    f\"Got invalid JSON object. Error: {e_json} {e_yaml}. \"\n                    f\"Got JSON string: {json_string}\"\n                )\n            except NameError as exc:\n                raise ImportError(\"Please pip install PyYAML.\") from exc\n\n        if isinstance(json_obj, dict):\n            json_obj = [json_obj]\n\n        if not isinstance(json_obj, list):\n            raise ValueError(f\"Failed to convert output to JSON: {output!r}\")\n\n        json_output = self._format_output(json_obj)\n        answers = [Answer.from_dict(json_dict) for json_dict in json_output]\n        return StructuredOutput(raw_output=output, parsed_output=answers)\n\n    def format(self, prompt_template: str) -> str:\n        return prompt_template + \"\\n\\n\" + _escape_curly_braces(FORMAT_STR)\n","sourceCodeStart":79,"sourceCodeEnd":105,"githubUrl":"https://github.com/run-llama/llama_index/blob/afd0fef371831f9bda13e5af7167cf4e981278ab/llama-index-core/llama_index/core/output_parsers/selection.py#L79-L105","documentation":"After successfully parsing the LLM string as JSON/YAML, SelectionOutputParser normalizes a dict to a one-element list; if the parsed object is anything else (a bare string, number, or boolean), it raises ValueError('Failed to convert output to JSON: {output!r}'). The selection schema requires an array (or single object) of choice entries.","triggerScenarios":"Model returns a plain string like '\"Paris\"' or a number (e.g. via yaml fallback parsing 'yes'/'42'), or a YAML scalar ('answer' parses as the string 'answer') instead of the expected [{answer: ..., score: ...}] structure; also markdown-fenced content where the outer parse yields a scalar.","commonSituations":"Prompts where the model replies with just the choice text instead of the JSON structure; selection templates modified/customized so the FORMAT_STR contract is broken; very small models echoing the query.","solutions":["Restore/keep the original selection prompt format string so the model emits the documented JSON array","Pre-validate parsed output yourself if wrapping the parser: accept only dict/list, re-prompt otherwise","Use a model with reliable instruction following for selection/routing","Catch the ValueError (and OutputParserException) around the query call and retry with an explicit schema reminder"],"exampleFix":"# before\n# model output: 'yes'  -> yaml parses to bool True -> ValueError: Failed to convert output to JSON\nresponse = selector.select(options)\n\n# after\nfrom llama_index.core.output_parsers import OutputParserException\ntry:\n    response = selector.select(options)\nexcept (OutputParserException, ValueError):\n    response = selector.select(options, prompt_extra=\"Respond ONLY as a JSON array per the schema.\")","handlingStrategy":"validation","validationCode":"import json\nobj = json.loads(llm_output)  # or yaml.safe_load\nif not isinstance(obj, (dict, list)):\n    raise ValueError(f\"selection output is a scalar ({obj!r}); re-prompt for JSON array\")","typeGuard":"def is_selection_shape(obj) -> bool:\n    return isinstance(obj, (dict, list)) and (not isinstance(obj, list) or all(isinstance(i, dict) for i in obj))","tryCatchPattern":"try:\n    result = selector.select(prompt)\nexcept ValueError as e:\n    if \"Failed to convert output to JSON\" in str(e):\n        result = selector.select(prompt, prompt_extra=\"Return ONLY the JSON array per the schema.\")\n    else:\n        raise","preventionTips":["Keep the stock selection FORMAT_STR prompt so models emit the JSON array","Catch both ValueError and OutputParserException around selection calls and re-prompt once","Test selection prompts against your weakest supported model"],"tags":["llm","output-parsing","json","schema","routing"],"backgroundTag":null,"analyzedSha":"afd0fef371831f9bda13e5af7167cf4e981278ab","analyzedAt":"2026-08-15T05:42:58.429Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}