{"record":{"id":"75c751a89ed0160a","repo":"json-path/JsonPath","slug":"target-index-larger-than-object-count","errorCode":null,"errorMessage":"Target index: larger than object count:","messagePattern":"Target index: larger than object count:","errorType":"exception","errorClass":"JsonPathException","httpStatus":null,"severity":"error","filePath":"json-path/src/main/java/com/jayway/jsonpath/internal/function/sequence/AbstractSequenceAggregation.java","lineNumber":36,"sourceCode":"    \n    protected abstract int targetIndex(EvaluationContext ctx, List<Parameter> parameters);\n    \n    @Override\n    public Object invoke(String currentPath, PathRef parent, Object model, EvaluationContext ctx, List<Parameter> parameters) {\n        if(ctx.configuration().jsonProvider().isArray(model)){\n\n            Iterable<?> objects = ctx.configuration().jsonProvider().toIterable(model);\n            List<Object> objectList = new ArrayList<>();\n            objects.forEach(objectList::add);\n            int targetIndex = this.targetIndex(ctx, parameters);\n            if (targetIndex >= 0) {\n                return objectList.get(targetIndex);\n            } else {\n                int realIndex = objectList.size() + targetIndex;\n                if (realIndex > 0) {\n                    return objectList.get(realIndex);\n                } else {\n                    throw new JsonPathException(\"Target index:\" + targetIndex + \" larger than object count:\" + objectList.size());\n                }\n            }\n        }\n        throw new JsonPathException(\"Aggregation function attempted to calculate value using empty array\");\n    }\n    \n    protected int getIndexFromParameters(EvaluationContext ctx, List<Parameter> parameters) {\n        List<Number> numbers = Parameter.toList(Number.class, ctx, parameters);\n        return numbers.get(0).intValue();\n    }\n}\n","sourceCodeStart":18,"sourceCodeEnd":48,"githubUrl":"https://github.com/json-path/JsonPath/blob/62a4c9f0f65ba3f625aa0867d64c528ba72d09ec/json-path/src/main/java/com/jayway/jsonpath/internal/function/sequence/AbstractSequenceAggregation.java#L18-L48","documentation":"Sequence functions (first(), last(), index(n), slice()) select an element by index from the target array. When a positive target index exceeds the last position of the list (or the wrapped negative index computation fails), AbstractSequenceAggregation.invoke throws JsonPathException('Target index:N larger than object count:M').","triggerScenarios":"Using functions like $.arr.index(5) or $.arr.first() when the array has fewer elements than the requested index — e.g. index(5) on a 3-element array — via JsonPath.read().","commonSituations":"Requesting a fixed position from variable-length arrays (e.g. 'always take the 10th sensor reading'), off-by-one assumptions about array size, or documents from different environments having shorter arrays than expected.","solutions":["Verify array length before applying the index, or use functions that tolerate short arrays.","Catch JsonPathException and fall back to a default value for missing positions.","Use index(-1)/last() semantics carefully; negative indices count from the end and can also exceed bounds.","Guard upstream with $[?(@.arr.length() >= N)] filters before selecting."],"exampleFix":"// before\nObject v = JsonPath.read(json, \"$.readings.index(9)\"); // only 3 readings\n// after\nList<Object> r = JsonPath.read(json, \"$.readings\");\nObject v = (r != null && r.size() > 9) ? r.get(9) : null;","handlingStrategy":"validation","validationCode":"List<?> arr = JsonPath.read(json, \"$.readings\");\nObject v = (arr != null && arr.size() > 9) ? arr.get(9) : null;","typeGuard":null,"tryCatchPattern":"try {\n    return JsonPath.read(json, \"$.readings.index(9)\");\n} catch (JsonPathException e) {\n    if (e.getMessage().startsWith(\"Target index\")) return null; // index out of bounds\n    throw e;\n}","preventionTips":["Check list size before fixed-index selection","Prefer last()/first() over index(n) when position is relative to the end","Treat array length as variable across environments/documents"],"tags":["json-path","index-out-of-bounds","sequence"],"backgroundTag":"index-out-of-range","analyzedSha":"62a4c9f0f65ba3f625aa0867d64c528ba72d09ec","analyzedAt":"2026-09-11T11:36:00.448Z","contentChangedAt":"2026-09-11T11:36:00.448Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}