首頁 >後端開發 >Golang >如何在 Go 中用指數解組 JSON 數值?

如何在 Go 中用指數解組 JSON 數值?

Patricia Arquette
Patricia Arquette原創
2024-11-15 13:59:03212瀏覽

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.

以上是如何在 Go 中用指數解組 JSON 數值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn