In my Go code, I was working to unmarshal a JSON payload we receive from an endpoint. This endpoint encodes large values in scientific notation:
type Test struct {
Key string
Value int32
}
func main() {
data := []byte("{\"Key\": \"derp\", \"Value\": 3.898733e+06}")
var t *Test
err := json.Unmarshal(data, &t)
fmt.Printf("Error: %v\n", err)
fmt.Printf("Data: %v\n", t)
}
The encoded value here is equivalent to 3,898,733 in standard notation. However, this code prints an error:
json: cannot unmarshal number 3.898733e+06 into Go struct field Test.Value of type int32
This makes sense because strconv
also fails to parse this value from a string. However, I can do var i int32 = 3.898733e+06
and that compiles and produces the correct answer.
So, how can I address this error?