Skip to content

Commit f4dd9f5

Browse files
HC Hagenbuger
authored andcommitted
Minor fixes to panics on certain errors, with complementary unit test (can be deleted).
1 parent 2cac668 commit f4dd9f5

File tree

2 files changed

+49
-3
lines changed

2 files changed

+49
-3
lines changed

parser.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,10 @@ func searchKeys(data []byte, keys ...string) int {
242242

243243
// if string is a key, and key level match
244244
if data[i] == ':' && keyLevel == level-1 {
245+
if level < 1 {
246+
return -1
247+
}
248+
245249
key := data[keyBegin:keyEnd]
246250

247251
// for unescape: if there are no escape sequences, this is cheap; if there are, it is a
@@ -439,9 +443,11 @@ func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]str
439443
}
440444
}
441445

442-
switch data[i] {
443-
case '{', '}', '[', '"':
444-
i--
446+
if i < ln {
447+
switch data[i] {
448+
case '{', '}', '[', '"':
449+
i--
450+
}
445451
}
446452
} else {
447453
i--

parser_error_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package jsonparser
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
var testPaths = [][]string{
9+
[]string{"test"},
10+
[]string{"these"},
11+
[]string{"keys"},
12+
[]string{"please"},
13+
}
14+
15+
func testIter(data []byte) (err error) {
16+
EachKey(data, func(idx int, value []byte, vt ValueType, iterErr error) {
17+
if iterErr != nil {
18+
err = fmt.Errorf("Error parsing json: %s", iterErr.Error())
19+
}
20+
}, testPaths...)
21+
return err
22+
}
23+
24+
func TestPanickingErrors(t *testing.T) {
25+
if err := testIter([]byte(`{"test":`)); err == nil {
26+
t.Error("Expected error...")
27+
}
28+
29+
if err := testIter([]byte(`{"test":0}some":[{"these":[{"keys":"some"}]}]}some"}]}],"please":"some"}`)); err == nil {
30+
t.Error("Expected error...")
31+
}
32+
33+
if _, _, _, err := Get([]byte(`{"test":`), "test"); err == nil {
34+
t.Error("Expected error...")
35+
}
36+
37+
if _, _, _, err := Get([]byte(`{"some":0}some":[{"some":[{"some":"some"}]}]}some"}]}],"some":"some"}`), "x"); err == nil {
38+
t.Error("Expected error...")
39+
}
40+
}

0 commit comments

Comments
 (0)