Search code examples
gotypestype-assertion

Check if a value is an int


So Im sending this payload to my app :

{
    "name" : "Matias Barrios",
    "age" : 123
}

The problem I am facing is that when I test if name is a string it works perfectly. But test if age is an int is always returning false, no matter what I do.

if gjson.Get(spec, "name").Exists() {
            if _, ok := gjson.Get(spec, "name").Value().(string); !ok {
                n := validator_error{Path: "_.name", Message: "should be a string"}
                errors = append(errors,n)
            }
}

if gjson.Get(spec, "age").Exists() {
            if _, ok := gjson.Get(spec, "age").Value().(int); !ok {
                n := validator_error{Path: "_.age", Message: "should be an int"}
                errors = append(errors,n)
            }

        }

Could someone tell me where is the error here?

Note - I am using this https://github.com/tidwall/gjson to get the values out of the JSON.


Solution

  • It seems like this lib for json numbers it return float64

    bool, for JSON booleans
    float64, for JSON numbers
    string, for JSON string literals
    nil, for JSON null