【问题标题】:Test type of value in GoGo中值的测试类型
【发布时间】:2018-01-16 17:03:36
【问题描述】:

我正在尝试在 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)

提前致谢!

【问题讨论】:

    标签: arrays json object go typeof


    【解决方案1】:

    使用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

    【讨论】:

    • 非常感谢!你的第二个例子正是我所需要的!
    【解决方案2】:

    当您将类型打印到控制台时,它会转换为字符串;但是,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 Kindsreflect.Stringreflect.Map

    【讨论】:

      【解决方案3】:

      reflect.TypeOf 返回一个Type 对象。请参阅https://golang.org/pkg/reflect/#TypeOf 的文档

      您的代码应为:

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

      【讨论】:

        猜你喜欢
        • 2022-10-14
        • 2016-02-22
        • 2014-06-15
        • 2011-10-16
        • 2016-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多