Skip to content

Commit

Permalink
encoding/json: make Number with the ,string option marshal with quotes
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
breml authored and mvdan committed Sep 16, 2019
1 parent c1e020b commit b9a29a0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
6 changes: 6 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 4 additions & 1 deletion encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)
Expand Down

0 comments on commit b9a29a0

Please sign in to comment.