Home > Backend Development > Golang > Why Does Golang JSON Unmarshal Error When Encountering Numeric Values with Exponents?

Why Does Golang JSON Unmarshal Error When Encountering Numeric Values with Exponents?

Mary-Kate Olsen
Release: 2024-11-15 19:21:02
Original
733 people have browsed it

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"`
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template