Home > Article > Backend Development > How to Unmarshal JSON Numeric Values with Exponents in Go?
JSON Unmarshal of Numeric Values with Exponents
Golang users may encounter difficulties when attempting to unmarshal JSON strings into Go structures containing numeric values with exponents. By default, Go misinterprets these values, resulting in a loss of precision.
Problem Demonstration
Consider the following Go code:
type Person struct { Id uint64 `json:"id"` Name string `json:"name"` } func parseJSON(jsonStr []byte) { var person Person json.Unmarshal(jsonStr, &person) // The numeric value with an exponent is lost. fmt.Println(person.Id) }
When we provide a JSON string like { "id": 1.2E 8, "name": "John" } as input, the parseJSON function prints 0, indicating that the exponent is being ignored.
Solution
To resolve this issue, adjust the type of the Id field to a floating-point type such as float64, as demonstrated below:
type Person struct { Id float64 `json:"id"` Name string `json:"name"` }
This modification allows Go to correctly interpret the exponent and preserve the numerical value.
Alternative Approach with Hooks
For cases where changing the field type is not feasible, you can employ a workaround involving a "dummy" field and a custom hook. This hook would cast the value from the "dummy" field to the desired integer type.
type Person struct { Id float64 `json:"id"` _Id int64 Name string `json:"name"` } func parseJSONWithHook(jsonStr []byte) { var person Person json.Unmarshal(jsonStr, &person) if reflect.TypeOf(person._Id) == reflect.TypeOf((int64)(0)) { person._Id = int64(person.Id) } }
By following either approach, you can successfully handle numeric values with exponents in your Go programs.
The above is the detailed content of How to Unmarshal JSON Numeric Values with Exponents in Go?. For more information, please follow other related articles on the PHP Chinese website!