Preserve int64 value for map[string]interface{}

Hello Gos,

I have a problem with this (I have to stay in a generic form because I’m using this method for all kind of queries):

			genericBody = map[string]interface{}{}
			dec := json.NewDecoder(genericResp.Body)
			err = dec.Decode(&genericBody)

It transform this:

{
  "data": {
    "list": [
      {
        "advertiser_id": 6868310788839309317,
        "advertiser_name": "fggddf"
      }
    ]
  },
}

to:

{
   "data":{
      "list":[
         {
            "advertiser_id":6868310788839309000,
            "advertiser_name":"fggddf"
         }
      ]
   },
}

this:
6868310788839309000
become:
6868310788839309317

it looks like it doesn’t preserve the full int64…

I auto reply:

		dec := json.NewDecoder(genericResp.Body)
		dec.UseNumber()
		err = dec.Decode(&genericBody)

Still have the issue when writing the payload to the client:

{
“ads_provider_profiles”: [
{
“id”: 6868310788839309000,
}
]
}

This is probably because of the JSON being inherently coupled to JavaScript and it’s flaws.

If you need exact numbers, use a string.

1 Like

9007199254740991, which is far less than OP’s number 6868310788839309317.

However, the hex representation of 6868310788839309317 is 0x5f512445c7c00005. Due to all those zeros preceding the trailing 5, which can be absorbed in the floating point exponent, means that a roundtrip from int64 to float64 and back only loses the 5.

package main
import "fmt"

func main() {
	n := 6868310788839309317
	jsmaxint := 9007199254740991
	fmt.Println(jsmaxint)
	fmt.Println(n)
	fmt.Println(int64(float64(n)))
	fmt.Printf("%x\n", n)
	fmt.Printf("%x\n", int64(float64(n)))
}
9007199254740991
6868310788839309317
6868310788839309312
5f512445c7c00005
5f512445c7c00000
1 Like

Wahoo thank you so much for this explanation

whenever dealing with Numbers as Numbers in JSON you should always use “BigNumbers”, in Go this means using the math/big package.

Otherwise, encode them as a string and not have to worry about the IEEE float conversion.

Thank you so much