Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion simplejson.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]}
}
}
Expand Down
29 changes: 29 additions & 0 deletions simplejson_index_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}