You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It's common for dynamic languages to be somewhat lax about the distinction
between an array and a single value when encoding and decoding JSON.
For example, a single value may be generated where an array is also acceptable.
Currently this can be worked around by defining a special type
for the slice being unmarshaled to.
For example:
type Val struct {
S string
}
type Vals []Val
func (r *Vals) UnmarshalJSON(data []byte) error {
type noUnmarshal Vals
if data[0] == '[' {
return json.Unmarshal(data, (*noUnmarshal)(r))
}
*r = make(Vals, 1)
return json.Unmarshal(data, &(*r)[0])
}
This is cumbersome. Instead we could make encoding/json automatically
allow a singleton value when decoding into a slice, or provide an
struct tag option to enable that behaviour.
The text was updated successfully, but these errors were encountered:
If it's common I'm a little surprised it hasn't come up already. Can you point to specific JSON implementations that don't care and are causing problems? I mean, JavaScript clearly distinguishes between [1] and 1 for example.
Ping. Any new context here? I'm still skeptical this is a common problem.
rsc
changed the title
proposal: encoding/json should provide an easy way to unmarshal singletons into a slice
proposal: encoding/json: allow unmarshaling singleton into slice
Apr 17, 2017
It's common for dynamic languages to be somewhat lax about the distinction
between an array and a single value when encoding and decoding JSON.
For example, a single value may be generated where an array is also acceptable.
Currently this can be worked around by defining a special type
for the slice being unmarshaled to.
For example:
This is cumbersome. Instead we could make encoding/json automatically
allow a singleton value when decoding into a slice, or provide an
struct tag option to enable that behaviour.
The text was updated successfully, but these errors were encountered: