Home >Backend Development >Golang >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}]}
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 }
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 }
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!