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: failed to get the correct value of large number using json.Unmarshal #12409

Closed
libnat opened this issue Aug 31, 2015 · 4 comments

Comments

@libnat
Copy link

libnat commented Aug 31, 2015

json.Unmarshal parse number into float64 by default.
if the number is int64, the result is not correct.
It is suggested to use json.Number instead of float64.
However, lots of packages just use json.Unmarshal instead of explicitly specify json.Number.
e.g.

//golang.org/x/net/websocket  
websocket.JSON.receive use json.Unmarshal to parse json object

Could encoding/json package use json.Number as the default number type?

@kostya-sh
Copy link
Contributor

Representing int64 values as numbers in JSON is not very good idea. It won't work in javascript as well (and possibly other languages/packages). E.g. in Chrome:

> JSON.parse('{\"x\": 1152921504606846976}')
< Object {x: 1152921504606847000}

The implementation in Go also conforms to RFC 7159 recommendation: http://rfc7159.net/rfc7159#rfc.section.6

@libnat
Copy link
Author

libnat commented Aug 31, 2015

@kostya-sh Thanks for your reply.
I just read that document and realise that int64 is not well supported in JSON.
In my project, int64 is used to represent 64 bits id. It is widely used.
I admit this is not an issue.
It would be better to support int64 by default. It is well supported in libraries on Android and iOS platform.

@rsc
Copy link
Contributor

rsc commented Oct 23, 2015

No, for compatibility reasons the default cannot be changed.

Note that when decoding into an int64, there is no problem. The float64 default only matters when decoding into an interface{} value, which is already a less-than-ideal way to use package json. Better to decode into a typed data structure.

Even for decoding into an interface{} value, the choice can be changed by calling json.Decoder's UseNumber method before decoding.

@rsc rsc closed this as completed Oct 23, 2015
@libnat
Copy link
Author

libnat commented Nov 11, 2015

@rsc Thanks for your reply. You are right. There is no problem to decode into an int64. Only matters when decoding into an interface{} value. I recall that if decode the json data into map[string]interface{}, it would matter. But if decode it directly into a struct with int64 as its field, it would be fine.

@golang golang locked and limited conversation to collaborators Nov 10, 2016
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

4 participants