{"record":{"id":"c28085876b358b49","repo":"run-llama/llama_index","slug":"invalid-json-path-expression","errorCode":null,"errorMessage":"Invalid JSON Path: {expression}","messagePattern":"Invalid JSON Path: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"warning","filePath":"llama-index-core/llama_index/core/indices/struct_store/json_query.py","lineNumber":85,"sourceCode":"    try:\n        from jsonpath_ng.ext import parse  # pants: no-infer-dep\n        from jsonpath_ng.jsonpath import DatumInContext  # pants: no-infer-dep\n    except ImportError as exc:\n        IMPORT_ERROR_MSG = \"You need to install jsonpath-ng to use this function!\"\n        raise ImportError(IMPORT_ERROR_MSG) from exc\n\n    results: Dict[str, str] = {}\n\n    for expression in expressions:\n        try:\n            datum: List[DatumInContext] = parse(expression).find(json_value)\n            if datum:\n                key = expression.split(\".\")[\n                    -1\n                ]  # Extracting \"title\" from \"$.title\", for example\n                results[key] = \", \".join(str(i.value) for i in datum)\n        except Exception as exc:\n            raise ValueError(f\"Invalid JSON Path: {expression}\") from exc\n\n    return results\n\n\nclass JSONQueryEngine(BaseQueryEngine):\n    \"\"\"\n    GPT JSON Query Engine.\n\n    Converts natural language to JSON Path queries.\n\n    Args:\n        json_value (JSONType): JSON value\n        json_schema (JSONType): JSON schema\n        json_path_prompt (BasePromptTemplate): The JSON Path prompt to use.\n        output_processor (Callable): The output processor that executes the\n            JSON Path query.\n        output_kwargs (dict): Additional output processor kwargs for the\n            output_processor function.","sourceCodeStart":67,"sourceCodeEnd":103,"githubUrl":"https://github.com/run-llama/llama_index/blob/afd0fef371831f9bda13e5af7167cf4e981278ab/llama-index-core/llama_index/core/indices/struct_store/json_query.py#L67-L103","documentation":"After the LLM emits one or more JSONPath expressions, default_output_processor parses each with jsonpath_ng. If parse(expression) or .find(json_value) throws (malformed syntax, or an expression the extension parser rejects), the exception is wrapped in ValueError('Invalid JSON Path: <expression>').","triggerScenarios":"The model hallucinating invalid syntax like '$..title[' or '$.store.book[*].authors()[0]' variants the parser rejects; expressions containing stray text from the prompt (the code strips 'JSONPath: ' prefixes and splits on ',', so commas inside filter expressions like $.a[?(@.x>1,2)] also corrupt expressions); querying JSON whose shape differs from what the model assumed.","commonSituations":"Smaller/weaker models producing non-JSONPath output; few-shot examples in default_output_parser_prompt that teach wrong syntax; commas in the natural-language answer leaking into the expression list; JSON payloads that changed shape between prompt construction and query.","solutions":["Retry the query (LLM output varies run to run) or lower temperature to reduce malformed output","Provide better few-shot examples via a custom json_path_prompt covering the syntax you expect","Pre-validate/sanitize: only forward answers matching a JSONPath sanity regex before parsing, and split on newlines instead of commas if your prompts allow it","Use JSONAdapter/JSONQueryEngine with a stronger model for accurate path generation"],"exampleFix":"# before\nresponse = query_engine.query(\"what is the title and the price?\")\n\n# after (catch and retry with tighter prompt)\nfrom llama_index.core.output_parsers.utils import parse_json_markdown\nfor attempt in range(3):\n    try:\n        response = query_engine.query(\"what is the title? (answer with a single JSONPath)\")\n        break\n    except ValueError as e:\n        continue","handlingStrategy":"retry","validationCode":"import re\nJSONPATH_RE = re.compile(r'^\\$[^,]*$')\nraw = llm_output.replace('JSONPath: ', '').strip()\nexpressions = [e.strip() for e in raw.split(',') if JSONPATH_RE.match(e.strip())]\nif not expressions:\n    raise ValueError('no valid JSONPath expressions in LLM output')","typeGuard":"def looks_like_jsonpath(expr: str) -> bool:\n    return bool(expr) and expr.lstrip().startswith('$') and not any(c.isspace() for c in expr)","tryCatchPattern":"for attempt in range(3):\n    try:\n        response = query_engine.query(query_str)\n        break\n    except ValueError as e:\n        if 'Invalid JSON Path' not in str(e) or attempt == 2:\n            raise","preventionTips":["Keep temperature low for JSONPath generation tasks","Give few-shot examples of the exact path syntax your JSON needs","Avoid queries that invite comma-separated multi-path answers, or split on newlines in a custom output parser"],"tags":["llama-index","json","llm-output","jsonpath","parsing"],"backgroundTag":null,"analyzedSha":"afd0fef371831f9bda13e5af7167cf4e981278ab","analyzedAt":"2026-08-15T05:42:58.429Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}