From 445cc4c1af47910e479042882f99d9f973b6c258 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Fri, 21 Aug 2020 01:12:29 +0900 Subject: [PATCH] Fix encoding of json.Number --- encode_test.go | 22 ++++++++++++++++++++++ json.go | 3 +++ 2 files changed, 25 insertions(+) diff --git a/encode_test.go b/encode_test.go index d3f622b..4ef90f9 100644 --- a/encode_test.go +++ b/encode_test.go @@ -1211,3 +1211,25 @@ func TestUnsupportedValues(t *testing.T) { } } } + +func TestIssue10281(t *testing.T) { + type Foo struct { + N json.Number + } + x := Foo{json.Number(`invalid`)} + + b, err := json.Marshal(&x) + if err == nil { + t.Errorf("Marshal(&x) = %#q; want error", b) + } +} + +func TestHTMLEscape(t *testing.T) { + var b, want bytes.Buffer + m := `{"M":"foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `"}` + want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`)) + json.HTMLEscape(&b, []byte(m)) + if !bytes.Equal(b.Bytes(), want.Bytes()) { + t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) + } +} diff --git a/json.go b/json.go index 0b49c31..5b51102 100644 --- a/json.go +++ b/json.go @@ -297,6 +297,9 @@ func (n Number) Int64() (int64, error) { } func (n Number) MarshalJSON() ([]byte, error) { + if _, err := n.Float64(); err != nil { + return nil, err + } return []byte(n), nil }