Home > Backend Development > Golang > How to Unmarshal JSON Numeric Values with Exponents in Go?

How to Unmarshal JSON Numeric Values with Exponents in Go?

Patricia Arquette
Release: 2024-11-15 13:59:03
Original
212 people have browsed it

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

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

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

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!

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