How Can I Parse JSON Integers as Integers, Not Floats, in Golang?

Linda Hamilton
Release: 2024-11-17 02:24:03
Original
187 people have browsed it

How Can I Parse JSON Integers as Integers, Not Floats, in Golang?

Parsing JSON Integers As Integers, Not Floats in Golang

In Golang, parsing JSON integer values as floats is a common problem. The default encoding/json package does not distinguish between integer and float numbers, leading to data type conflicts and write failures when interacting with databases. To address this issue, we can employ alternative approaches for parsing JSON values.

Custom JSON Values for Number Types

One solution is to utilize the general Go mechanism for custom JSON values. By implementing a custom JSON type that differentiates between integers and floats, we can control the data type conversion process. An example implementation is shown below:

type MyInt int64

func (mi MyInt) MarshalJSON() ([]byte, error) {
    return []byte(strconv.FormatInt(int64(mi), 10)), nil
}
Copy after login

This custom type converts integer values to strings when marshaling them into JSON. To unmarshal JSON values into custom types, we can use a json.Unmarshal function:

var raw map[string]interface{}
err := json.Unmarshal([]byte(str), &raw)
parsed := make(map[string]interface{}, len(raw))
for key, val := range raw {
    s := string(val)
    i, err := strconv.ParseInt(s, 10, 64)
    if err == nil {
        parsed[key] = MyInt(i)
        continue
    }

    // Handle other types as needed
}
Copy after login

Using the json.Number Type

Another approach involves the use of json.Number, a type that represents JSON numbers. It provides methods for converting the number to int64 and float64 values, allowing us to manually handle the type conversion:

var parsed map[string]interface{}
d := json.NewDecoder(strings.NewReader(str))
d.UseNumber()
err := d.Decode(&parsed)
for key, val := range parsed {
    n, ok := val.(json.Number)
    if !ok {
        continue
    }
    if i, err := n.Int64(); err == nil {
        parsed[key] = i
        continue
    }
    if f, err := n.Float64(); err == nil {
        parsed[key] = f
        continue
    }
}
Copy after login

The above is the detailed content of How Can I Parse JSON Integers as Integers, Not Floats, in Golang?. 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