diff options
author | Lucas Bremgartner <lucas@bremis.ch> | 2019-09-13 19:46:50 +0000 |
---|---|---|
committer | Daniel Martí <mvdan@mvdan.cc> | 2019-09-16 11:56:15 +0000 |
commit | 49e7c7672d6d065435f7058df90b082cb552c7dd (patch) | |
tree | c40efe6f98a52d3d0423dde073222cb79f6f7a3e /src/encoding/json | |
parent | d9b8ffa51cf7cafe18107ec53a4ec3ceff15ce46 (diff) | |
download | go-49e7c7672d6d065435f7058df90b082cb552c7dd.tar.gz go-49e7c7672d6d065435f7058df90b082cb552c7dd.zip |
encoding/json: make Number with the ,string option marshal with quotes
Add quotes when marshaling a json.Number with the string option
set via a struct tag. This ensures that the resulting json
can be unmarshaled into the source struct without error.
Fixes #34268
Change-Id: Ide167d9dec77019554870b5957b37dc258119d81
GitHub-Last-Rev: dde81b71208be01c253bb87dbb6f81ac6e0785be
GitHub-Pull-Request: golang/go#34269
Reviewed-on: https://go-review.googlesource.com/c/go/+/195043
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Diffstat (limited to 'src/encoding/json')
-rw-r--r-- | src/encoding/json/encode.go | 6 | ||||
-rw-r--r-- | src/encoding/json/encode_test.go | 5 |
2 files changed, 10 insertions, 1 deletions
diff --git a/src/encoding/json/encode.go b/src/encoding/json/encode.go index e5dd1b7799..b4fba476c8 100644 --- a/src/encoding/json/encode.go +++ b/src/encoding/json/encode.go @@ -600,7 +600,13 @@ func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) { if !isValidNumber(numStr) { e.error(fmt.Errorf("json: invalid number literal %q", numStr)) } + if opts.quoted { + e.WriteByte('"') + } e.WriteString(numStr) + if opts.quoted { + e.WriteByte('"') + } return } if opts.quoted { diff --git a/src/encoding/json/encode_test.go b/src/encoding/json/encode_test.go index 18a92bae7c..8d3503b1ba 100644 --- a/src/encoding/json/encode_test.go +++ b/src/encoding/json/encode_test.go @@ -76,13 +76,15 @@ type StringTag struct { IntStr int64 `json:",string"` UintptrStr uintptr `json:",string"` StrStr string `json:",string"` + NumberStr Number `json:",string"` } var stringTagExpected = `{ "BoolStr": "true", "IntStr": "42", "UintptrStr": "44", - "StrStr": "\"xzbit\"" + "StrStr": "\"xzbit\"", + "NumberStr": "46" }` func TestStringTag(t *testing.T) { @@ -91,6 +93,7 @@ func TestStringTag(t *testing.T) { s.IntStr = 42 s.UintptrStr = 44 s.StrStr = "xzbit" + s.NumberStr = "46" got, err := MarshalIndent(&s, "", " ") if err != nil { t.Fatal(err) |