Skip to content

Commit

Permalink
Use MarshalJSON() of the wrapped Go value if available
Browse files Browse the repository at this point in the history
  • Loading branch information
dop251 committed Jun 30, 2017
1 parent a6ed999 commit 8f3380f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
7 changes: 7 additions & 0 deletions builtin_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,13 @@ func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool {
case *objectGoReflect:
if o1.toJson != nil {
value = ctx.r.ToValue(o1.toJson())
} else if v, ok := o1.origValue.Interface().(json.Marshaler); ok {
b, err := v.MarshalJSON()
if err != nil {
panic(err)
}
ctx.buf.Write(b)
return true
} else {
switch o1.className() {
case classNumber:
Expand Down
14 changes: 14 additions & 0 deletions builtin_json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"strings"
"testing"
"time"
)

func TestJSONMarshalObject(t *testing.T) {
Expand All @@ -20,6 +21,19 @@ func TestJSONMarshalObject(t *testing.T) {
}
}

func TestJSONMarshalGoDate(t *testing.T) {
vm := New()
o := vm.NewObject()
o.Set("test", time.Unix(86400, 0).UTC())
b, err := json.Marshal(o)
if err != nil {
t.Fatal(err)
}
if string(b) != `{"test":"1970-01-02T00:00:00Z"}` {
t.Fatalf("Unexpected value: %s", b)
}
}

func TestJSONMarshalObjectCircular(t *testing.T) {
vm := New()
o := vm.NewObject()
Expand Down

0 comments on commit 8f3380f

Please sign in to comment.