Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: encoding/json: allow unmarshaling singleton into slice #19854

Closed
rogpeppe opened this issue Apr 5, 2017 · 3 comments
Closed

proposal: encoding/json: allow unmarshaling singleton into slice #19854

rogpeppe opened this issue Apr 5, 2017 · 3 comments

Comments

@rogpeppe
Copy link
Contributor

rogpeppe commented Apr 5, 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:

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.

@rsc
Copy link
Contributor

rsc commented Apr 5, 2017

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.

@gopherbot gopherbot added this to the Proposal milestone Apr 5, 2017
@rsc
Copy link
Contributor

rsc commented Apr 17, 2017

Ping. Any new context here? I'm still skeptical this is a common problem.

@rsc 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
@rsc
Copy link
Contributor

rsc commented Jun 12, 2017

Closing for lack of motivation.

@rsc rsc closed this as completed Jun 12, 2017
@golang golang locked and limited conversation to collaborators Jun 12, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants