所以我将此有效负载发送到我的应用程序:
{
"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中获取值。
答案 0 :(得分:2)
对于json数字,它似乎是这个lib,它返回float64
bool, for JSON booleans
float64, for JSON numbers
string, for JSON string literals
nil, for JSON null
答案 1 :(得分:1)
在github.com/tidwall/gjson中,结果类型只能为json数字保存float64。
虽然您可以使用Int()而不是Value()来获取整数值。
fmt.Println(gjson.Get(spec, "age").Int()) // 123
答案 2 :(得分:0)
您可以使用ALTER TABLE 'table_name' ALTER COLUMN 'column_name' TYPE varchar(100);
字段检查类型:
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