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

encoding/json: interface{} not being stringified when JSON ",string" tag is used #32055

Open
docmerlin opened this issue May 15, 2019 · 2 comments

Comments

Projects
None yet
3 participants
@docmerlin
Copy link

commented May 15, 2019

What version of Go are you using (go version)?

1.12.5 playground

Does this issue reproduce with the latest release?

yes

What operating system and processor architecture are you using (go env)?

NACL

What did you do?

https://play.golang.org/p/Q4JdghzkBI-

What did you expect to see?

interface{} fields that point to integers should be converted to strings when the string tag is used.

The documentation says:
It applies only to fields of string, floating point, integer, or boolean types

but it also says:

Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON value.

What did you see instead?

They were not converted to strings.

@andybons andybons changed the title interface{} not being stringified when JSON ",string" tag is used encoding/json: interface{} not being stringified when JSON ",string" tag is used May 15, 2019

@FiloSottile

This comment has been minimized.

Copy link
Member

commented May 15, 2019

@FiloSottile FiloSottile added this to the Go1.14 milestone May 15, 2019

@andybons

This comment has been minimized.

Copy link
Member

commented May 15, 2019

This is due to the encoder determining whether to quote the value while looking at the type of field (in this case reflect.Interface within typeFields). Since there are only a subset of types permitted and reflect.Interface is not one of them, quoted is never set to true. So when it gets to the intEncoder it’s not quoting the value.

Adding reflect.Interface to the list of allowed types has the desired effect for an int, but then if you put a slice of strings into the field, it will recursively encode the types and quote them, so you’ll end up with

{"Thing": ["\"val\""]} instead of the desired {"Thing": ["val"]}

The same is true for maps and any other data structure where it needs to recursively encode values.

This isn’t to say we shouldn’t fix these cases, but it provides some context as to why this is happening.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.