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

How to Preserve Int64 Precision When Parsing JSON in Go?

Mary-Kate Olsen
Release: 2024-12-08 07:32:27
Original
217 people have browsed it

How to Preserve Int64 Precision When Parsing JSON in Go?

Preserve Int64 Values When Parsing JSON in Go

When parsing JSON data in Go, the json.Unmarshal function often converts large integer values to float64 types, which can be problematic for maintaining precision.

Solution 1:

To preserve the original int64 values, use a decoder and the UseNumber option:

package main

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

func main() {
    body := []byte("{\"tags\":[{\"id\":4418489049307132905},{\"id\":4418489049307132906}]}")
    d := json.NewDecoder(bytes.NewBuffer(body))

    // Enable number preservation
    d.UseNumber()

    var dat map[string]interface{}
    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:

Alternatively, you can decode directly into a custom data structure:

package main

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

Caution:

Note that JavaScript's number type is IEEE754 double precision float, which means it cannot represent 64-bit integers without losing precision.

The above is the detailed content of How to Preserve Int64 Precision When Parsing JSON 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