检查值是否为 int

Check if a value is an int

所以我将此有效负载发送到我的应用程序:

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

我面临的问题是,当我测试 name 是否是一个字符串时,它工作得很好。但是无论我做什么,测试 age 是否是一个 int 总是返回 false。

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)
            }

        }

谁能告诉我这里的错误在哪里?

注意 - 我正在使用此 https://github.com/tidwall/gjson 从 JSON 中获取值。

这个 json 的库似乎是它的编号 return float64

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

如 github.com/tidwall/gjson 结果类型只能为 json 数字保留 float64。

尽管您可以使用 Int() 而不是 Value() 来获取整数值。

fmt.Println(gjson.Get(spec, "age").Int())  // 123

您可以使用 result.Type 字段来检查类型:

res := gjson.Get(spec, "age")
if res.Type != gjson.Number {
    n := validator_error{Path: "_.age", Message: "should be an int"}
}

如果您要求该值为整数 123 而不是 123.5:

res := gjson.Get(spec, "age")
if res.Type != gjson.Number || math.Floor(res.Num) != res.Num {
    n := validator_error{Path: "_.age", Message: "should be an int"}
}