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

How to Unmarshal JSON Numeric Values with Exponents in Golang?

Mary-Kate Olsen
Release: 2024-11-15 10:31:02
Original
1069 people have browsed it

How to Unmarshal JSON Numeric Values with Exponents in Golang?

Golang Json Unmarshal Numeric with Exponent

When unmarshaling a JSON string into a struct in Golang, numeric values with exponents are often interpreted as 0. This can be a challenge, as exponents are a standard part of the JSON specification.

To address this issue, the type of the numeric field must be modified to either float32 or float64. These floating-point types support the representation of exponents. For example:

type Person struct {
    Id    float64          `json:"id"`
    _Id   int64             
    Name  string           `json:"name"`
}
Copy after login

After changing the type, unmarshaling the JSON string into the struct will correctly parse the numeric value with the exponent.

Alternative Approach with a Helper Function

If you require the numeric field to be an integer, you can use a helper function to cast the floating-point value to the integer type after unmarshaling:

import (
    "encoding/json"
    "fmt"
    "math"
    "os"
    "reflect"
)

type Person struct {
    Id    float64          `json:"id"`
    _Id   int64             
    Name  string           `json:"name"`
}

var f Person
var b = []byte(`{"id": 1.2e+8, "Name": "Fernando"}`)

func main() {
    _ = json.Unmarshal(b, &f)

    if reflect.TypeOf(f._Id) == reflect.TypeOf((int64)(0)) {
        fmt.Println(math.Trunc(f.Id))
        f._Id = int64(f.Id)
    }
}
Copy after login

In this example, the helper function math.Trunc truncates the floating-point value to an integer. The truncated value is then assigned to the _Id field.

The above is the detailed content of How to Unmarshal JSON Numeric Values with Exponents in Golang?. For more information, please follow other related articles on the PHP Chinese website!

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