diff --git a/simplejson.go b/simplejson.go index 486fe49..b0cd848 100644 --- a/simplejson.go +++ b/simplejson.go @@ -149,7 +149,7 @@ func (j *Json) GetPath(branch ...string) *Json { func (j *Json) GetIndex(index int) *Json { a, err := j.Array() if err == nil { - if len(a) > index { + if index >= 0 && index < len(a) { return &Json{a[index]} } } diff --git a/simplejson_index_test.go b/simplejson_index_test.go new file mode 100644 index 0000000..7e86a6d --- /dev/null +++ b/simplejson_index_test.go @@ -0,0 +1,29 @@ +package simplejson + +import "testing" + +func TestGetIndexBounds(t *testing.T) { + for _, body := range []string{`[]`, `["first", "last"]`, `null`, `{}`} { + j, err := NewJson([]byte(body)) + if err != nil { + t.Fatal(err) + } + for _, index := range []int{-int(^uint(0)>>1) - 1, -1, 2, int(^uint(0) >> 1)} { + if got := j.GetIndex(index); got == nil || got.Interface() != nil { + t.Errorf("GetIndex(%d) on %s = %#v, want a null Json", index, body, got) + } + } + } + j, err := NewJson([]byte(`["first", "last"]`)) + if err != nil { + t.Fatal(err) + } + for i, want := range []string{"first", "last"} { + if got := j.GetIndex(i).MustString(); got != want { + t.Errorf("GetIndex(%d) = %q, want %q", i, got, want) + } + } + if got := j.GetIndex(-1).Get("missing").MustString("fallback"); got != "fallback" { + t.Fatalf("chained missing index = %q", got) + } +}