JSON Number Handling — int vs float64 in Go

Understand how Go handles JSON numbers: when to use int, float64, or json.Number. Covers precision issues, large integers, and numeric string parsing.

Edge Cases

Detailed Explanation

JSON Number Types in Go

JSON has a single number type, but Go distinguishes between int, int64, float64, and more. Choosing the right type matters for correctness and precision.

Default Behavior

When unmarshaling into interface{}, all JSON numbers become float64:

var data map[string]interface{}
json.Unmarshal([]byte(`{"id": 9007199254740993}`), &data)
// data["id"] is float64, loses precision!

float64 can only represent integers up to 2^53 precisely. Larger IDs (like Twitter snowflake IDs) lose precision.

Using json.Number

decoder := json.NewDecoder(reader)
decoder.UseNumber()

With UseNumber(), JSON numbers unmarshal as json.Number (a string type), preserving the original text:

n := data["id"].(json.Number)
id, _ := n.Int64()  // precise

Type Selection Guide

JSON value Go type When to use
42 int Small integers, counts, IDs
9007199254740993 int64 Large integers, timestamps
3.14 float64 Decimal numbers, coordinates
"42" int with string tag Numbers sent as strings
any number json.Number When you need the raw text

Struct Field Types

type Transaction struct {
    ID     int64   `json:"id"`
    Amount float64 `json:"amount"`
    Count  int     `json:"count"`
}

The converter analyzes the sample JSON: numbers with decimals become float64, whole numbers become int. Very large numbers may trigger int64.

Numbers as Strings

Some APIs quote numbers: "amount": "19.99". Use the string tag option:

Amount float64 `json:"amount,string"`

Precision-Critical Applications

For financial data, avoid float64 entirely. Parse the string representation and use an arbitrary-precision library or store cents as int64.

Use Case

Social media platforms use 64-bit snowflake IDs that exceed float64 precision. Financial APIs send amounts as strings to avoid rounding. Understanding Go's number handling prevents subtle data corruption bugs.

Try It — JSON to Go Struct Converter

Open full tool