go-gorm / datatypes

GORM Customized Data Types Collection
https://gorm.io/docs/data_types.html
MIT License
698 stars 107 forks source link

Use json.Number when scan to JSONMap #202

Closed levanlongktmt closed 1 year ago

levanlongktmt commented 1 year ago

What did this pull request do?

Use json.Decoder.UseNumber() when Scan []byte to JSONMap

User Case Description

When scanning JSONMap (a.k.a map[string]interface{}) from []byte, it returns the incorrect value of int64 and uint64 if the value is more than 18 digits. The reason is by default json.Unmarshal treat int64 and uint64 as float64 and loses the numeric precision. For example

content := `{"user_id": 1085238870184050699, "name": "Name of user"}`
obj := make(datatypes.JSONMap)
obj.Scan([]byte(content))
fmt.Print(obj["user_id"])
// before: obj["user_id"] = 1.0852388701840507e+18 <-- incorrect value
// after: obj["user_id"] = 1085238870184050699 <-- correct value
fmt.Print(cast.ToInt64(obj["user_id"])) // use github.com/spf13/cast
// before: obj["user_id"] = 1085238870184050688 <-- incorrect value
// after: obj["user_id"] = 1085238870184050699 <-- correct value