-
Notifications
You must be signed in to change notification settings - Fork 17.9k
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
encoding/json: marshal of custom type not quoted when using ",string" tag field #20651
Comments
You are using a custom marshal function, not sure why is that unexpected? |
Perhaps the package docs should be improved to clarify that |
@OneOfOne + @mvdan The primary concern is the inconsistency between reading/writing JSON. Note that the quoting is removed when parsing JSON but not added when creating JSON. The inconsistency can be addressed either by supporting quoting when serializing Both options have backwards-compatibility issues, as programs are likely to have already worked around the observed behavior. |
Marking for Go2 due to backwards-incompatible changes that would need to be made. |
@aronatkins I've found the solution... type BigInt struct {
_bi big.Int
}
func (bi BigInt) String() string {
return bi._bi.String()
}
// before
//func (bi BigInt) MarshalJSON() ([]byte, error) {
// return []byte(bi._bi.String()), nil
//}
// now
func (bi BigInt) MarshalJSON() ([]byte, error) {
return []byte(`"` + bi._bi.String() + `"`), nil
} You jus need to add the I fixed this issue by using the tricks above. @totoval For your example, |
Signed-off-by: Toby Yan <me@tobyan.com>
Please answer these questions before submitting your issue. Thanks!
What version of Go are you using (
go version
)?What operating system and processor architecture are you using (
go env
)?What did you do?
We receive JSON which encodes booleans as numeric strings. Parsing that JSON works just fine with a
",string"
tag and a type with its ownUnmarshalJSON
definition. The quoting is removed and we get the proper boolean value.Quoting is not added when serializing this type, which means that JSON IN>decode>encode>OUT produces OUT different than IN.
https://play.golang.org/p/ccIw4E6UJF
What did you expect to see?
Equivalent support for
",string"
for this custom type when both encoding and decoding. I was surprised by the difference in behavior. Both cases should either err (becauseparsedBool
is notbool
) or properly handle the quotes.The json docs state:
What did you see instead?
Given:
This is marshaled as:
This was unexpected because we properly parse:
The text was updated successfully, but these errors were encountered: