我试图在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)
提前致谢!
答案 0 :(得分:3)
当您将类型打印到控制台时,它会转换为字符串;但是,as you can see from the documentation for TypeOf
,它不返回string
,而是返回reflect.Type
。您可以使用Kind()
以编程方式测试它的内容:
if reflect.TypeOf(gjson.Get(api_spec, "tags").Value()).Kind() != reflect.Slice {
您可能感兴趣的 Other Kind
s是reflect.String
和reflect.Map
。
答案 1 :(得分:3)
使用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{}
答案 2 :(得分:1)
reflect.TypeOf
会返回Type
个对象。请参阅https://golang.org/pkg/reflect/#TypeOf
您的代码应为:
if reflect.TypeOf(gjson.Get(api_spec, "tags").Value()).Name() != "[]interface {}" {
// some code here ...
}