Skip to content

Commit

Permalink
Fix array-like handling in JSON.stringify
Browse files Browse the repository at this point in the history
This fixes robertkrimen#73
  • Loading branch information
robertkrimen committed May 24, 2014
1 parent ba678bc commit b7dd9df
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
13 changes: 13 additions & 0 deletions bug_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,19 @@ func Test_issue64(t *testing.T) {
})
}

func Test_issue73(t *testing.T) {
tt(t, func() {
test, vm := test()

vm.Set("abc", [4]int{3, 2, 1, 0})

test(`
var def = [ 0, 1, 2, 3 ];
JSON.stringify(def) + JSON.stringify(abc);
`, "[0,1,2,3][3,2,1,0]")
})
}

func Test_7_3_1(t *testing.T) {
tt(t, func() {
test(`
Expand Down
13 changes: 12 additions & 1 deletion builtin_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package otto
import (
"bytes"
"encoding/json"
"fmt"
"math"
"strings"
)
Expand Down Expand Up @@ -250,7 +251,17 @@ func builtinJSON_stringifyWalk(ctx _builtinJSON_stringifyContext, key string, ho
defer func() { ctx.stack = ctx.stack[:len(ctx.stack)-1] }()
}
if isArray(holder) {
length := holder.get("length").value.(uint32)
var length uint32
switch value := holder.get("length").value.(type) {
case uint32:
length = value
case int:
if value >= 0 {
length = uint32(value)
}
default:
panic(newTypeError(fmt.Sprintf("JSON.stringify: invalid length: %v (%[1]T)", value)))
}
array := make([]interface{}, length)
for index, _ := range array {
name := arrayIndexToString(int64(index))
Expand Down

0 comments on commit b7dd9df

Please sign in to comment.