Home > Backend Development > Golang > How to Handle JSON Numerals with Exponents in Go?

How to Handle JSON Numerals with Exponents in Go?

Susan Sarandon
Release: 2024-11-17 08:03:03
Original
343 people have browsed it

How to Handle JSON Numerals with Exponents in Go?

Decoding JSON Numerals with Exponents in Go

When unmarshaling JSON data into a Go structure, numeric values with exponents are often misinterpreted as zero. This occurs when the target field in the structure is declared as an integer type.

To address this issue, follow these steps:

  1. Modify the Field Type: Change the type of the field where the numeric value with exponent will be stored from uint64 to float32 or float64. For example:
type Person struct {
    Id   float32  `json:"id"`
    Name string `json:"name"`
}
Copy after login
  1. Unmarshal the JSON: Perform the unmarshaling operation as usual using the json.Unmarshal function. The numeric values with exponents will now be correctly interpreted.

Here is an example:

package main

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

type Person struct {
    Id   float32  `json:"id"`
    Name string `json:"name"`
}

func main() {

    // Create the JSON string.
    var b = []byte(`{"id": 1.2E+8, "Name": "Fernando"}`)

    // Unmarshal the JSON to a proper struct.
    var f Person
    json.Unmarshal(b, &f)

    // Print the person.
    fmt.Println(f)

    // Unmarshal the struct to JSON.
    result, _ := json.Marshal(f)

    // Print the JSON.
    os.Stdout.Write(result)
}
Copy after login

This will output:

{1.2e+08 Fernando}
{"id":1.2e+08,"Name":"Fernando"}
Copy after login

Alternative Approach:

If you must use an integer type for the field, you can employ a "dummy" field of type float64 to capture the numeric value with exponent. Then, use a hook to cast the value to the actual integer type.

Here is an example:

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"}`)
_ = 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 will output:

1.2e+08
{Name:Fernando Id:120000000}
Copy after login

The above is the detailed content of How to Handle JSON Numerals 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