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

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

Patricia Arquette
發布: 2024-11-15 13:59:03
原創
220 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板