json.Unmarshal causing big integer value to change?

525 views
Skip to first unread message

stephen....@gmail.com

unread,
Apr 29, 2014, 1:16:28 PM4/29/14
to golan...@googlegroups.com
Hi guys,

Not sure how this is happening exactly, but it looks like when I try to unmarshal JSON containing large integers as values the resulting floating point value is slightly off:


Is there anything I'm doing wrong here? I don't necessarily know the name or type of the property in advance so I have to parse into a map[string]interface{}.

Any insight would be much appreciated.

Matthew Kane

unread,
Apr 29, 2014, 1:22:07 PM4/29/14
to stephen....@gmail.com, golang-nuts
That number is beyond the range where float64 can represent all
integers exactly. If you know that you will be using integers that
big, and they'll be integers every time, you can use a json.Decoder,
which will unmarshal to a json.Number
http://golang.org/pkg/encoding/json/#Number

Example: http://play.golang.org/p/lTe4da3Q0b
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--
matt kane
twitter: the_real_mkb / nynexrepublic
http://hydrogenproject.com

Rui Ueyama

unread,
Apr 29, 2014, 1:50:00 PM4/29/14
to Matthew Kane, stephen....@gmail.com, golang-nuts
Note that other JSON encoders/decoders may not be able to handle that large number exactly too, so "fixing" it in your Go code may not solve the entire issue. I'd think you want to change the type of "id" from number to string if you can change the format.

Stephen Huenneke

unread,
Apr 29, 2014, 1:52:15 PM4/29/14
to Rui Ueyama, Matthew Kane, golang-nuts
Yeah, I'm not in charge of the format (otherwise we'd marshal to a struct), it comes in from other sources and we are essentially an intermediary for some processing. The decoder approach will work just fine, we're not re-serializing it after it's loaded into our program anyway.

Thanks for the help!
--
///Stephen - http://sdh.skarilla.com
Reply all
Reply to author
Forward
0 new messages