From 681b17fcb70353c8c7bcc0fda3d2fcf830a1518c Mon Sep 17 00:00:00 2001 From: Charlie Tonneslan Date: Mon, 25 May 2026 10:34:44 -0400 Subject: [PATCH] fix: don't panic in searchKeys when an empty path component meets an array For a Get call like jsonparser.Get([]byte("[]"), "") the searchKeys '[' case reached `keys[level][0] == '['` with an empty `keys[level]` and indexed into a zero-length string, panicking with index out of range. Guard the index access so an empty key falls through to the array-skip branch and surfaces as KeyPathNotFoundError, matching the behaviour for the object case (`Get([]byte("{}"), "")`). Closes #247 Signed-off-by: Charlie Tonneslan --- parser.go | 2 +- parser_test.go | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/parser.go b/parser.go index d8df1678..d358856d 100644 --- a/parser.go +++ b/parser.go @@ -322,7 +322,7 @@ func searchKeys(data []byte, keys ...string) int { } case '[': // If we want to get array element by index - if keyLevel == level && keys[level][0] == '[' { + if keyLevel == level && len(keys[level]) > 0 && keys[level][0] == '[' { keyLen := len(keys[level]) // Note: keys[level][0] == '[' is guaranteed by the outer if-guard, // so the former middle term `keys[level][0] != '['` was always false diff --git a/parser_test.go b/parser_test.go index 795b4706..ddcc531e 100644 --- a/parser_test.go +++ b/parser_test.go @@ -1170,6 +1170,18 @@ var getArrayTests = []GetTest{ isFound: true, data: []string{`1`, `2`, `3`, `4`}, }, + { + desc: `array with single empty-string key returns not-found, not panic`, + json: `[]`, + path: []string{""}, + isFound: false, + }, + { + desc: `truncated array with empty key returns not-found, not panic`, + json: `[`, + path: []string{""}, + isFound: false, + }, { desc: `read array of objects`, json: `{"a": { "b":[{"x":1},{"x":2},{"x":3},{"x":4}]}}`,