Golang 使用 JSON unmarshal 数字到 interface{} 数字变成 float64 类型

碰到这个问题一脸疑惑,后来不断谷歌才找到答案,小白用户献上解析如下:

这是由于 JSON 里的数字默认都会转成 Golang 的 float64 类型引起的,

使用 Golang 解析 JSON  格式数据时,若以 interface{} 接收数据,则会按照下列规则进行解析:

    bool, for JSON booleans

    float64, for JSON numbers

    string, for JSON strings

    []interface{}, for JSON arrays

    map[string]interface{}, for JSON objects

    nil for JSON null

而浮点数打印时的默认规则是超过一定长度后会换成科学计数法打印。

因此,只要在打印时指定打印格式,或者(按照LZ示例里是整数的情况时),转换为整数打印

fmt.Println( int( a["id"].(float64) ) ) // 将 “id” 键申明为 float64 类型,再转换为 int 型

猜你喜欢

转载自blog.csdn.net/chuanglan/article/details/77390406