Commit 49e7c767 authored by Lucas Bremgartner's avatar Lucas Bremgartner Committed by Daniel Martí

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/+/195043Reviewed-by: default avatarDaniel Martí <mvdan@mvdan.cc>
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
parent d9b8ffa5
...@@ -600,7 +600,13 @@ func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) { ...@@ -600,7 +600,13 @@ func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) {
if !isValidNumber(numStr) { if !isValidNumber(numStr) {
e.error(fmt.Errorf("json: invalid number literal %q", numStr)) e.error(fmt.Errorf("json: invalid number literal %q", numStr))
} }
if opts.quoted {
e.WriteByte('"')
}
e.WriteString(numStr) e.WriteString(numStr)
if opts.quoted {
e.WriteByte('"')
}
return return
} }
if opts.quoted { if opts.quoted {
......
...@@ -76,13 +76,15 @@ type StringTag struct { ...@@ -76,13 +76,15 @@ type StringTag struct {
IntStr int64 `json:",string"` IntStr int64 `json:",string"`
UintptrStr uintptr `json:",string"` UintptrStr uintptr `json:",string"`
StrStr string `json:",string"` StrStr string `json:",string"`
NumberStr Number `json:",string"`
} }
var stringTagExpected = `{ var stringTagExpected = `{
"BoolStr": "true", "BoolStr": "true",
"IntStr": "42", "IntStr": "42",
"UintptrStr": "44", "UintptrStr": "44",
"StrStr": "\"xzbit\"" "StrStr": "\"xzbit\"",
"NumberStr": "46"
}` }`
func TestStringTag(t *testing.T) { func TestStringTag(t *testing.T) {
...@@ -91,6 +93,7 @@ func TestStringTag(t *testing.T) { ...@@ -91,6 +93,7 @@ func TestStringTag(t *testing.T) {
s.IntStr = 42 s.IntStr = 42
s.UintptrStr = 44 s.UintptrStr = 44
s.StrStr = "xzbit" s.StrStr = "xzbit"
s.NumberStr = "46"
got, err := MarshalIndent(&s, "", " ") got, err := MarshalIndent(&s, "", " ")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment