diff --git a/parser.go b/parser.go index 2da0323..8c88242 100644 --- a/parser.go +++ b/parser.go @@ -267,19 +267,23 @@ func searchKeys(data []byte, keys ...string) int { keyUnesc = ku } - if equalStr(&keyUnesc, keys[level-1]) { - lastMatched = true - - // if key level match - if keyLevel == level-1 { - keyLevel++ - // If we found all keys in path - if keyLevel == lk { - return i + 1 + if level <= len(keys) { + if equalStr(&keyUnesc, keys[level-1]) { + lastMatched = true + + // if key level match + if keyLevel == level-1 { + keyLevel++ + // If we found all keys in path + if keyLevel == lk { + return i + 1 + } } + } else { + lastMatched = false } } else { - lastMatched = false + return -1 } } else { i-- @@ -490,10 +494,11 @@ func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]str if len(p) < level+1 || pathFlags&bitwiseFlags[pi+1] != 0 || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) { continue } - - aIdx, _ := strconv.Atoi(p[level][1 : len(p[level])-1]) - arrIdxFlags |= bitwiseFlags[aIdx+1] - pIdxFlags |= bitwiseFlags[pi+1] + if len(p[level]) >= 2 { + aIdx, _ := strconv.Atoi(p[level][1 : len(p[level])-1]) + arrIdxFlags |= bitwiseFlags[aIdx+1] + pIdxFlags |= bitwiseFlags[pi+1] + } } if arrIdxFlags > 0 { diff --git a/parser_test.go b/parser_test.go index 40685cf..cd3ccb4 100644 --- a/parser_test.go +++ b/parser_test.go @@ -814,6 +814,13 @@ var getTests = []GetTest{ isFound: true, data: `1`, }, + { + // Issue #178: Crash in searchKeys + desc: `invalid json`, + json: `{{{"":`, + path: []string{"a", "b"}, + isFound: false, + }, } var getIntTests = []GetTest{ @@ -1479,6 +1486,7 @@ func TestEachKey(t *testing.T) { {"arrInt", "[3]"}, {"arrInt", "[5]"}, // Should not find last key {"nested"}, + {"arr", "["}, // issue#177 Invalid arguments } keysFound := 0 @@ -1525,6 +1533,8 @@ func TestEachKey(t *testing.T) { if string(value) != `{"a":"test", "b":2, "nested3":{"a":"test3","b":4}, "c": "unknown"}` { t.Error("Should find 9 key", string(value)) } + case 10: + t.Errorf("Found key #10 that should not be found") default: t.Errorf("Should find only 9 keys, got %v key", idx) }