JSON UseNumber Preserves Big Numbers
Decode JSON numbers as json.Number with UseNumber so integers beyond float64's 2^53 keep every digit instead of silently losing precision.
Code
package main
import (
"bytes"
"encoding/json"
"fmt"
)
func main() {
payload := []byte(`{"order_id":9007199254740993,"amount":49.95}`)
// 默认解码:整数落进 float64,超过 2^53 精度丢失
var sloppy struct {
OrderID float64 `json:"order_id"`
}
_ = json.Unmarshal(payload, &sloppy)
fmt.Println("float64 order_id:", sloppy.OrderID)
// UseNumber:数字按 json.Number(字符串底座)保留原样
dec := json.NewDecoder(bytes.NewReader(payload))
dec.UseNumber()
var exact map[string]any
if err := dec.Decode(&exact); err != nil {
fmt.Println("decode:", err)
return
}
if n, err := exact["order_id"].(json.Number).Int64(); err == nil {
fmt.Println("json.Number order_id:", n)
}
fmt.Println("amount as number:", exact["amount"].(json.Number).String())
}The machinery at work
Count the function main as the entire surface area of JSON UseNumber Preserves Big Numbers.
Nothing falls through silently — 1 checkpoint test err != nil on the way through.
Applying it
The run emits 4 labeled sections — float64 order_id:, decode:, json.Number order_id:, amount as number: — one per step.
Statements that matter
payload := []byte(`{"order_id":9007199254740993,"amount":49.95}`)
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What does JSON UseNumber Preserves Big Numbers print when run?
- The script runs standalone; its 4 labeled outputs include `float64 order_id:`, `decode:`, `json.Number order_id:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.