Skip to content

Commit

Permalink
encoding/json: fix marshal for json.Number ,string
Browse files Browse the repository at this point in the history
Add quotes if a value of type json.Number with the string option
(struct tag) set is marshaled. This ensures, that the resulting json
can be unmarshaled into the source struct without error.

Fixes golang#34268
  • Loading branch information
breml committed Sep 12, 2019
1 parent 6c6ad30 commit dde81b7
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/encoding/json/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 src/encoding/json/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 dde81b7

Please # to comment.