Home > Article > Backend Development > Why Does Golang JSON Unmarshal Error When Encountering Numeric Values with Exponents?
Golang JSON Unmarshal Error: Numeric Values with Exponents Return 0
While attempting to unmarshal JSON data into a Go struct, users have encountered an issue where numeric values with exponents are consistently being interpreted as 0. This behavior stems from a mismatch between the expected type and the actual value.
For example, if a JSON string like {"id": 1.2e 8, "Name": "Fernando"} is to be unmarshalled into a struct with an Id field of type uint64, the resulting Id will be 0.
Solution
To resolve this issue, ensure that the type of the field in the struct matches the type of the data in the JSON string. In this case, since exponents are used, the Id field should be defined as a floating-point type like float32 or float64.
Alternative Solution
For situations where the expected type is not compatible with the JSON numeric format, a workaround can be implemented. By adding a "dummy" field of the desired type, a hook can be used to cast the value to the actual expected type.
For instance:
type Person struct { Id float64 `json:"id"` _Id int64 Name string `json:"name"` }
After unmarshalling the JSON data into the Person struct, a conditional check can be added to cast the Id field to int64.
var f Person var b = []byte(`{"id": 1.2e+8, "Name": "Fernando"}`) _ = json.Unmarshal(b, &f) if reflect.TypeOf(f._Id) == reflect.TypeOf((int64)(0)) { fmt.Println(f.Id) f._Id = int64(f.Id) }
This hacky approach allows for the conversion of the floating-point Id field to the desired int64 type.
The above is the detailed content of Why Does Golang JSON Unmarshal Error When Encountering Numeric Values with Exponents?. For more information, please follow other related articles on the PHP Chinese website!