I'm trying to get a value from a JSON and cast it to int but it doesn't work, and I don't know how to do it properly.
Here is the error message:
...cannot convert val (type interface {}) to type int: need type assertion
And the code:
var f interface{}
err = json.Unmarshal([]byte(jsonStr), &f)
if err != nil {
utility.CreateErrorResponse(w, "Error: failed to parse JSON data.")
return
}
m := f.(map[string]interface{})
val, ok := m["area_id"]
if !ok {
utility.CreateErrorResponse(w, "Error: Area ID is missing from submitted data.")
return
}
fmt.Fprintf(w, "Type = %v", val) // <--- Type = float64
iAreaId := int(val) // <--- Error on this line.
testName := "Area_" + iAreaId // not reaching here
Best Answer
Instead of
you want a type assertion:
The reason why you cannot convert an interface typed value are these rules in the referenced specs parts:
...
But
is not any of the cases 1.-7.