在 Go 中测试值的类型

Test type of value in Go

我正在尝试验证 Go 中的 JSON 对象。我正在尝试查看 'tags' 属性是否是一个数组。(稍后我还想知道另一个属性是否也是一个对象)。

我已经做到了。如果我打印 reflect.TypeOf(gjson.Get(api_spec, "tags").Value() 我得到:

string   // When the field is a string
[]interface {} // When the field is an array
map[string]interface {} // When the field is an object

但是当尝试在下面的代码中测试时:

if ( gjson.Get(api_spec, "tags").Exists() ) {
            if ( reflect.TypeOf(gjson.Get(api_spec, "tags").Value()) != "[]interface {}" ) {
             // some code here ...
            }
        }

我收到以下错误代码:

invalid operation: reflect.TypeOf(gjson.Get(api_spec, "tags").Value()) != "[]interface {}" (mismatched types reflect.Type and string)

提前致谢!

reflect.TypeOf returns 一个 Type 对象。请参阅 https://golang.org/pkg/reflect/#TypeOf

中的文档

您的代码应为:

if reflect.TypeOf(gjson.Get(api_spec, "tags").Value()).Name() != "[]interface {}" {
    // some code here ...
}

当您将类型打印到控制台时,它会转换为字符串;但是,as you can see from the documentation for TypeOf 不是 return string,而是 return reflect.Type。您可以使用 Kind() 以编程方式测试它是什么:

        if reflect.TypeOf(gjson.Get(api_spec, "tags").Value()).Kind() != reflect.Slice {

Other Kinds 您可能感兴趣的是 reflect.Stringreflect.Map

使用type assertion判断一个值是否为[]interface{}:

v := gjson.Get(api_spec, "tags").Value()
_, ok := v.([]interface{}) // ok is true if v is type []interface{}

问题中的代码已修改为使用类型断言:

if gjson.Get(api_spec, "tags").Exists() {
    if _, ok := gjson.Get(api_spec, "tags").Value().([]interface{}); !ok {
        // some code here ...
    }
}

没有必要使用反射。如果您出于某种原因确实想使用反射(并且我没有在问题中看到原因),请比较 reflect.Type 值:

// Get type using a dummy value. This can be done once by declaring
// the variable as a package-level variable.
var sliceOfInterface = reflect.TypeOf([]interface{}{})

ok = reflect.TypeOf(v) == sliceOfInterface  // ok is true if v is type []interface{}

run the code on the playground