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.

GoData Integrity

Code

gosnippet
31 lines
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

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:`.