dqce48404 2018-01-16 17:03
浏览 26
已采纳

在Go中测试值的类型

Im trying to validate a JSON object in Go. I'm trying to see if the 'tags' attribute is an array.( Later on I'll also want to know if another attribute is an object too).

I have reached to this. If I print reflect.TypeOf(gjson.Get(api_spec, "tags").Value() I get :

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

But when trying to test this on the below code :

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

I get the below error code :

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

Thanks in advance!

  • 写回答

3条回答 默认 最新

  • drvvepadi289421028 2018-01-16 17:45
    关注

    Use a type assertion to determine if a value is a []interface{}:

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

    Here's the code in the question modified to use a type assertion:

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

    There's no need to use reflection. If you do want to use reflection for some reason (and I don't see a reason in the question), then compare reflect.Type values:

    // 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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度