Go: Preserve large JSON integers with Decoder.UseNumber
Decoding a JSON number into any normally creates a float64. Some large integers cannot be represented exactly. Call UseNumber before decoding when the consumer needs to choose the numeric representation later.
Set up
Tested on Linux with Go 1.26.10. Use Bash with Go on your PATH. Keep the same terminal through cleanup, and stop if setup fails.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as json_usenumber_large_integers.go:
package main
import (
"encoding/json"
"fmt"
"strings"
)
func main() {
const input = `9007199254740993`
var ordinary any
if err := json.Unmarshal([]byte(input), &ordinary); err != nil {
panic(err)
}
fmt.Printf("default: %.0f\n", ordinary)
for _, text := range []string{input, "1.5", "9223372036854775808"} {
dec := json.NewDecoder(strings.NewReader(text))
dec.UseNumber()
var value any
if err := dec.Decode(&value); err != nil {
panic(err)
}
number, ok := value.(json.Number)
if !ok {
panic("expected a number")
}
n, err := number.Int64()
if err != nil {
fmt.Printf("%s: Int64 rejected\n", number)
continue
}
fmt.Printf("%s: Int64=%d\n", number, n)
}
}go run json_usenumber_large_integers.goObserved output:
default: 9007199254740992
9007199254740993: Int64=9007199254740993
1.5: Int64 rejected
9223372036854775808: Int64 rejectedRead the result
The default decode rounds the first input. Keeping its text as json.Number allows an exact signed 64-bit conversion. A fraction and a value above the signed 64-bit range still fail that conversion; preserving the token does not make every number fit an integer.
Apply it carefully
This example decodes fixed numeric literals and panics on unexpected setup errors. Validate types and return errors for external data. A single Decode call does not reject an additional JSON document after the first. When the schema is known, a typed integer field may express the requirement more directly.
See the Go standard-library reference.
Clean up
Remove the source and the empty scratch directory. Go may retain build-cache files outside this directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- json_usenumber_large_integers.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.