Home > Backend Development > Golang > How to Preserve Int64 Precision When Unmarshalling JSON in Go?

How to Preserve Int64 Precision When Unmarshalling JSON in Go?

Linda Hamilton
Release: 2024-12-29 06:04:15
Original
328 people have browsed it

How to Preserve Int64 Precision When Unmarshalling JSON in Go?

Preserve Int64 Values When Parsing JSON in Go

Consider the following JSON body:

{"tags": [{"id": 4418489049307132905}, {"id": 4418489049307132906}]}
Copy after login

When using json.Unmarshal() in Go to process this JSON, the 64-bit integer values (id) are often converted to float64 due to the nature of Go's JSON parser. This can be problematic if you need to preserve their precision.

Solution 1: Custom Decoder

One approach is to use a custom decoder and json.Number type. json.Number is a type that represents JSON number literals.

import (
    "encoding/json"
    "fmt"
    "bytes"
    "strconv"
)

func main() {
    body := []byte(`{"tags": [{"id": 4418489049307132905}, {"id": 4418489049307132906}]}`)
    dat := make(map[string]interface{})
    d := json.NewDecoder(bytes.NewBuffer(body))
    d.UseNumber()
    if err := d.Decode(&dat); err != nil {
        panic(err)
    }
    tags := dat["tags"].([]interface{})
    n := tags[0].(map[string]interface{})["id"].(json.Number)
    i64, _ := strconv.ParseUint(string(n), 10, 64)
    fmt.Println(i64) // Prints 4418489049307132905
}
Copy after login

Solution 2: Custom Structure

Another option is to decode the JSON into a custom structure that specifically matches your data format.

import (
    "encoding/json"
    "fmt"
)

type A struct {
    Tags []map[string]uint64 // "tags"
}

func main() {
    body := []byte(`{"tags": [{"id": 4418489049307132905}, {"id": 4418489049307132906}]}`)
    var a A
    if err := json.Unmarshal(body, &a); err != nil {
        panic(err)
    }
    fmt.Println(a.Tags[0]["id"]) // Logs 4418489049307132905
}
Copy after login

In this solution, uint64 is used directly in the structure, ensuring that 64-bit integer values are preserved.

The above is the detailed content of How to Preserve Int64 Precision When Unmarshalling JSON in Go?. 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