长整型数字精度丢失
import (
"bytes"
"encoding/json"
)
...
const userJson=`{"name":"Harvey","id":1514889703642370048}`
userInfo map[string]interface{}
infoBytes := []byte(userJson)
json.Unmarshal(infoBytes, &userInfo)
// json数值类型被定义为 interface{}, 使用 Unmarshal 方法后,只能被断言为float64
uid := userInfo["id"].(float64)
func JsonDecodeUseNumber(infoBytes []byte, result interface{}) error {
decoder := json.NewDecoder(bytes.NewReader(infoBytes))
// 未设置UseNumber, 长整型会丢失精度
decoder.UseNumber()
return decoder.Decode(result)
}
JsonDecodeUseNumber(infoBytes, &userInfo)
uidJNum := userInfo["id"].(json.Number)
uid := uidJNum.Int64()
...
jsonNumberjsonNumberinterface{}json.Unmarshalfloat64UseNumber()interface{}json.Number
json字符串包含非法字符
json.Unmarshal invalid character '\n' in string literal
import (
"bytes"
"encoding/json"
)
...
prodJson := `{"hel": "doafd",
"xxxdf": "aoifjadfoweih"}`
prodBytes := []byte(prodJson)
for i, ch := range prodBytes {
switch {
case ch > '~':
prodBytes[i] = ' '
case ch == '\r', ch == '\n', ch == '\t', ch < ' ':
prodBytes[i] = ' '
}
}
pd := map[string]string{}
json.Unmarshal(prodBytes, &pd)
...