JSON unmarshal Number to interface{} The number becomes float64 type
Use Golang analysis JSON When formatting data , If the interface{} Receive digital members , Then it will be parsed according to the following rules , so
Use Golang Yes JSON Structure (unmarshal) when ,JSON The number in the structure will be parsed as float64 type :
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
If you want to convert to integer , You can cast :
int( a["id"].(float64) ) // take interface{} Type of “id” The key is declared as float64 type , Re convert to int type
from :Golang Use JSON unmarshal Number to interface{} The number becomes float64 type
interface{} convert to int A general function of
func GetInterfaceToInt(t1 interface{}) int {
var t2 int
switch t1.(type) {
case uint:
t2 = int(t1.(uint))
break
case int8:
t2 = int(t1.(int8))
break
case uint8:
t2 = int(t1.(uint8))
break
case int16:
t2 = int(t1.(int16))
break
case uint16:
t2 = int(t1.(uint16))
break
case int32:
t2 = int(t1.(int32))
break
case uint32:
t2 = int(t1.(uint32))
break
case int64:
t2 = int(t1.(int64))
break
case uint64:
t2 = int(t1.(uint64))
break
case float32:
t2 = int(t1.(float32))
break
case float64:
t2 = int(t1.(float64))
break
case string:
t2, _ = strconv.Atoi(t1.(string))
break
default:
t2 = t1.(int)
break
}
return t2
}