参考文章:https://blog.cyeam.com/golang/2018/08/22/json-number

有些需求场景,我们不需要知道json完整数据结构,只需要针对其中个别字段做处理,再将其转换为json等等,这种情况下,可以将json解析为map[string]interface{}格式。
但是使用json.Unmarshal解析 会将数字解析为 float64格式,导致精度缺失、类型不符预期问题。

解决方案:
可使用Decoder.UseNumber函数,将数字解析为json.Number类型,再根据需要将其解析为期望格式。
特别说明:json.Number类型 转换为json时,会被转换为数字类型(good~

代码示例:

decoder := json.NewDecoder(bytes.NewBufferString(`{"10000000000":10000000000,"111":1}`))
decoder.UseNumber()
var obj map[string]interface{}
decoder.Decode(&obj)
for k, value := range obj {
	switch v := value.(type) {
	case json.Number:
		n, _ := v.Int64()
		obj[k] = n
	}
}
decoder := json.NewDecoder(bytes.NewBufferString(`{"10000000000":10000000000,"111":1}`))
decoder.UseNumber()
var obj map[string]interface{}
decoder.Decode(&obj)
b, _ := json.Marshal(&obj)
fmt.Println(string(b)) //{"10000000000":10000000000,"111":1}
Logo

鸿蒙生态一站式服务平台。

更多推荐