json.Unmarshal, json.Decoder.UseNumber, json.Number
func Unmarshal(data []byte, v any) error
func NewDecoder(r io.Reader) *Decoder
func (dec *Decoder) UseNumber()
func (dec *Decoder) Decode(v any) error
type Number string
func (n Number) Int64() (int64, error)Decode JSON numbers into float64 by default when the destination is any. UseNumber keeps the original decimal text so large integers can be parsed as int64.
| Parameter | Description |
|---|---|
data / r | The JSON input as bytes for Unmarshal, or as an io.Reader for a Decoder. |
v | A pointer to the destination value. Decoding into any stores bool, float64, string, []any, map[string]any, or nil. |
Returns: Unmarshal and Decode return nil on success. Number.Int64 returns the integer value or a syntax or range error.
Errors
error— Syntax errors, type errors, and I/O errors from the reader. Decode returns io.EOF when no more values remain.
- 9007199254740993 is 2^53 + 1. As float64 it becomes 9.007199254740992e+15, which is 2^53, not the original integer.
- UseNumber must be called before Decode. It does not convert values that have already been decoded as float64.
package main
import (
"encoding/json"
"fmt"
"strings"
)
func main() {
var value any
if err := json.Unmarshal([]byte(`{"n":9007199254740993}`), &value); err != nil {
panic(err)
}
n := value.(map[string]any)["n"]
fmt.Printf("%T %v\n", n, n)
dec := json.NewDecoder(strings.NewReader(`{"n":9007199254740993}`))
dec.UseNumber()
if err := dec.Decode(&value); err != nil {
panic(err)
}
num := value.(map[string]any)["n"].(json.Number)
i, err := num.Int64()
fmt.Printf("%T %s %d %v\n", num, num.String(), i, err)
}Expected output
float64 9.007199254740992e+15
json.Number 9007199254740993 9007199254740993 <nil>Related: JSON Diff tool, JSON to Go, json.Number