From b4ee365959e7a3687975f31e49136e5c163c0d97 Mon Sep 17 00:00:00 2001 From: erezrokah Date: Mon, 27 Feb 2023 16:11:17 +0200 Subject: [PATCH 1/2] fix(types-json): Disable HTML escaping during JSON marshalling --- schema/json.go | 8 ++++++-- schema/json_test.go | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/schema/json.go b/schema/json.go index b4c6c32610..b358934d20 100644 --- a/schema/json.go +++ b/schema/json.go @@ -124,13 +124,17 @@ func (dst *JSON) Set(src any) error { return &ValidationError{Type: TypeJSON, Msg: "use pointer to JSON instead of value", Value: value} default: - buf, err := json.Marshal(value) + buffer := &bytes.Buffer{} + encoder := json.NewEncoder(buffer) + encoder.SetEscapeHTML(false) + err := encoder.Encode(value) if err != nil { return err } + buf := buffer.Bytes() // For map and slice jsons, it is easier for users to work with '[]' or '{}' instead of JSON's 'null'. - if bytes.Equal(buf, []byte(`null`)) { + if bytes.Equal(buf, []byte("null\n")) { if isEmptyStringMap(value) { *dst = JSON{Bytes: []byte("{}"), Status: Present} return nil diff --git a/schema/json_test.go b/schema/json_test.go index 3cbd53fc7e..fffdb66773 100644 --- a/schema/json_test.go +++ b/schema/json_test.go @@ -43,6 +43,8 @@ func TestJSONSet(t *testing.T) { {source: map[string]Foo{}, result: JSON{Bytes: []byte(`{}`), Status: Present}}, {source: nil, result: JSON{Status: Null}}, + + {source: map[string]any{"test1": "a&b", "test2": "😀"}, result: JSON{Bytes: []byte(`{"test1": "a&b", "test2": "😀"}`), Status: Present}}, } for i, tt := range successfulTests { From 3539900fd5b44f529a823af594869aae0f2d2049 Mon Sep 17 00:00:00 2001 From: erezrokah Date: Thu, 2 Mar 2023 13:37:14 +0200 Subject: [PATCH 2/2] fix: Trim \n added by JSON encoder --- schema/json.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/schema/json.go b/schema/json.go index b358934d20..8ca70ec46a 100644 --- a/schema/json.go +++ b/schema/json.go @@ -132,9 +132,10 @@ func (dst *JSON) Set(src any) error { return err } - buf := buffer.Bytes() + // JSON encoder adds a newline to the end of the output that we don't want. + buf := bytes.TrimSuffix(buffer.Bytes(), []byte("\n")) // For map and slice jsons, it is easier for users to work with '[]' or '{}' instead of JSON's 'null'. - if bytes.Equal(buf, []byte("null\n")) { + if bytes.Equal(buf, []byte(`null`)) { if isEmptyStringMap(value) { *dst = JSON{Bytes: []byte("{}"), Status: Present} return nil