Go Json Unmarshal(反序列化) 丢失数字精度

现象

  • 业务会使用 id生成器 产生的 分布式唯一ID,长度比较长。代码反序列化时,出现精度丢失,导致线上故障。
go 复制代码
package main

import (
   "testing"
   "time"
   "github.com/bytedance/sonic"
   "github.com/stretchr/testify/assert"
)

func TestPrintAttr(t *testing.T) {
   amap := map[string]any{
      "psm_businessline_ref": map[string]any{
         "id": 1691071059696833999,
      },
   }

   amapStr, err := sonic.MarshalString(amap)
   assert.Nil(t, err)

   t.Log("\n", amapStr)

   m1 := make(map[string]any)
   err = sonic.UnmarshalString(amapStr, &m1)
   assert.Nil(t, err)
}

原因

  1. 反序列化时,对于数值类型的value,默认会反序列化成float64类型。
  2. float64可以存储的最大整数是52位尾数全位1且指数部分为最大 0x07FEF FFFF FFFF FFFF
ini 复制代码
(0x001F FFFF FFFF FFFF)16 = (9007199254740991)10 
(0x07EF FFFF FFFF FFFF)16 = (9218868437227405311)10 

也就是理论上数值超过9007199254740991(长度=16)就可能会出现精度缺失。

10进制数值的有效数字是16位,一旦超过16位大概率会有缺失精度的问题

一般分布式唯一id是20位长度,所以必然出现精度缺失。

参考:

解决方案

  • 使用 json.Decoder 来代替 json.Unmarshal 方法
go 复制代码
package main

import (
   "testing"
   "time"
   "github.com/bytedance/sonic"
   "github.com/stretchr/testify/assert"
)


func TestPrintAttr(t *testing.T) {
   amap := map[string]any{
      "psm_businessline_ref": map[string]any{
         "id": 1691071059696833999,
      },
   }

   amapStr, err := sonic.MarshalString(amap)
   assert.Nil(t, err)

   t.Log("\n", amapStr)

   rightM := make(map[string]any)
   if len(amapStr) > 0 {
      de := jsoniter.NewDecoder(bytes.NewReader([]byte(amapStr)))
      de.UseNumber()
      err := de.Decode(&rightM)

      if err != nil {
         t.Fatal(err)
      }
   }
   
}

json.Number本质是string,反序列化的时候将json的数值转成字符串 ,而字符串不会有精度丢失问题,所以没有问题。json.Number如下:

go 复制代码
package json
// A Number represents a JSON number literal.
type Number string
相关推荐
Mgx2 小时前
高性能 Go 语言带 TTL 的内存缓存实现:精确过期、自动刷新、并发安全
go
考虑考虑3 小时前
go格式化时间
后端·go
得物技术4 小时前
从 JSON 字符串到 Java 对象:Fastjson 1.2.83 全程解析|得物技术
java·后端·json
GISBox1 天前
GISBox如何让GeoTIFF突破Imagery Provider加载限制?
react.js·json·gis
光头闪亮亮1 天前
ZBar 条码/二维码识别工具介绍及golang通过cmd调用ZBar从图片中批量识别二维码
go
C嘎嘎嵌入式开发1 天前
(20)100天python从入门到拿捏《JSON 数据解析》
开发语言·python·json
东风t西瓜1 天前
golang项目开发环境配置
go
LazerYvTian1 天前
Json数据字段类型兼容性处理
json
weixin_307779132 天前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json
zhuyasen2 天前
在某些 Windows 版本,Go 1.25.x 编译出来的 exe 运行报错:此应用无法在你的电脑上运行
windows·go·编译器