From 594410467bc64b75c730dec01693270c735d2db1 Mon Sep 17 00:00:00 2001 From: Dmitry Panov Date: Tue, 24 Oct 2023 19:09:52 +0100 Subject: [PATCH] Correctly detect circular references in JSON.stringify for wrapped Go objects. Fixes #543. --- builtin_json.go | 2 +- builtin_json_test.go | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/builtin_json.go b/builtin_json.go index 9b69d902..e99771cf 100644 --- a/builtin_json.go +++ b/builtin_json.go @@ -359,7 +359,7 @@ func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool { ctx.buf.WriteString("null") case *Object: for _, object := range ctx.stack { - if value1 == object { + if value1.SameAs(object) { ctx.r.typeErrorResult(true, "Converting circular structure to JSON") } } diff --git a/builtin_json_test.go b/builtin_json_test.go index 3dfeba5b..a71c54e4 100644 --- a/builtin_json_test.go +++ b/builtin_json_test.go @@ -48,6 +48,23 @@ func TestJSONMarshalObjectCircular(t *testing.T) { } } +func TestJSONStringifyCircularWrappedGo(t *testing.T) { + type CircularType struct { + Self *CircularType + } + vm := New() + v := CircularType{} + v.Self = &v + vm.Set("v", &v) + _, err := vm.RunString("JSON.stringify(v)") + if err == nil { + t.Fatal("Expected error") + } + if !strings.HasPrefix(err.Error(), "TypeError: Converting circular structure to JSON") { + t.Fatalf("Unexpected error: %v", err) + } +} + func TestJSONParseReviver(t *testing.T) { // example from // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse