Skip to content

Commit 962fde5

Browse files
committed
Fix: Double-quoted types when encoded to JSON
When encoding map keys to JSON it will give priority to the `encoding.TextMarshaler` implementation, automatically adding quotes to the encoded value. If the encoding already add the quotes it will end up with a double-quoted JSON property that may cause issues in the decoding phase. From https://pkg.go.dev/encoding/json#Marshal: > The map's key type must either be a string, an integer type, or implement > encoding.TextMarshaler. > > * keys of any string type are used directly > * keys that implement encoding.TextMarshaler are marshaled > * integer keys are converted to strings
1 parent bd44192 commit 962fde5

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

types.go

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"io"
77
"net/http"
8+
"strconv"
89
"time"
910
)
1011

@@ -85,7 +86,16 @@ func (d *Date) UnmarshalJSON(data []byte) error {
8586

8687
// MarshalText encodes the Date as a string in the format "2006-01-02".
8788
func (d Date) MarshalText() ([]byte, error) {
88-
return d.MarshalJSON()
89+
quotedValue, err := d.MarshalJSON()
90+
if err != nil {
91+
return nil, err
92+
}
93+
// it is expected that encoding.TextMarshaler does not return quotes.
94+
value, err := strconv.Unquote(string(quotedValue))
95+
if err != nil {
96+
return nil, err
97+
}
98+
return []byte(value), nil
8999
}
90100

91101
// UnmarshalText decodes a text string into a Date type. This is required when
@@ -124,7 +134,16 @@ func (t *Time) UnmarshalJSON(data []byte) error {
124134

125135
// MarshalText encodes the Time as a string in the format "15:04:05".
126136
func (t Time) MarshalText() ([]byte, error) {
127-
return t.MarshalJSON()
137+
quotedValue, err := t.MarshalJSON()
138+
if err != nil {
139+
return nil, err
140+
}
141+
// it is expected that encoding.TextMarshaler does not return quotes.
142+
value, err := strconv.Unquote(string(quotedValue))
143+
if err != nil {
144+
return nil, err
145+
}
146+
return []byte(value), nil
128147
}
129148

130149
// UnmarshalText decodes a text string into a Time type. This is required when

0 commit comments

Comments
 (0)