Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON decoded value is treated as float64 instead of int

Tags:

go

I have a json response from a api as map[message:Login Success. userid:1]

Server:

c.JSON(200, gin.H{"message": "Login Success.", "userid": 1})

Client:

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)

msg, ok := result["message"].(string)
if !ok {
    msg = "Something went wrong."
}
userID, ok := result["userid"].(int)
if !ok {
    userID = 0
}

But userID, ok := result["userid"].(int) always fails. I've even tried using:

switch v := x.(type) {
case nil:
    fmt.Println("x is nil")          
case int: 
    fmt.Println("x is", v)           
case bool, string:
    fmt.Println("x is bool or string")
default:
    fmt.Println("type unknown")      
}

And it just gave me unknown. Why is the integer not being taken as integer?


It looks like its treating the value as float64.

like image 927
majidarif Avatar asked Mar 30 '19 23:03

majidarif


1 Answers

Here you can find the explanation why you are getting float64 and not int:

Check doc for Decode

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

And there see

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

float64, for JSON numbers
like image 155
Nik Avatar answered Nov 14 '22 12:11

Nik