-
Notifications
You must be signed in to change notification settings - Fork 17.8k
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: ability to unmarshal primitives as string #38516
Comments
It seems like there is a way to do this, and it's not going to be a common request. We generally resist adding new knobs to complex packages like encoding/json, because every new knob makes the package harder to use, harder to test, and harder to fix. Is there a compelling reason for us to add this to the package? Thanks. |
The documentation for json.Marshal says the following:
With the use of I do not have any other compelling reason. Feel free to close this issue if you disagree. As you mentioned |
I share @ianlancetaylor's thoughts. The options should only cover common use cases, and this seems niche enough that writing twenty lines of extra code seems fine. The code you shared above also seems pretty clean, to be honest. You can also make it behave any way you want, without having to worry about adding complex options to Really, this is exactly why the marshaler/unmarshaler interfaces were designed. They might be a bit cumbersome to use, but they are really powerful when it comes to custom encoding/decoding behavior. |
What version of Go are you using (
go version
)?What do you want?
At the moment we can unmarshal primitives from explicit types and strings if we use
json:",string"
for the value. My proposal is somewhat the oposit. I want to be able to create astring
from any primitives. Only primitives should apply, object and array types should returnjson.UnmarshalTypeError
.Example
Option 1 (preferred by me)
Explicit list of the acceptable types (and
null
).Option 2
json:",string"
on astring
type tells that all primitives should be converted to astring
.Why do you want this?
I have an endpoint where one of the field supposed to be a
string
. However, some clients uses dynamically typed languages to create the JSON and this causes an issue where the field which supposed to be astring
becomes anumber
instead. At the moment a customstring
type is used which implementsjson.Unmarshaler
.Example
The text was updated successfully, but these errors were encountered: