duandaishi9268 2017-04-27 13:54
浏览 77
已采纳

golang-将[]接口转换为[]字符串或连接的字符串

How can I convert []interface to []strings or just as a joined single string with all elements in []interface ? Below is the screenshot showing exact value of "scope" which of type []interface with length of 2. In below code, where case is "slice" Currently i am doing this using reflect but this is not looking good. Wondering there should be some good way to join a slice\array of interface elements.

I also did try using json unmarshall like this "json.Unmarshal([]byte(jwtResp),&mymap)" but having trouble with type issues in converting jwt.MapClaims to byte[]

parsedkey, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(key))
parsedToken, jwtErr := jwt.Parse(bearerToken, func(token *jwt.Token) (interface{}, error) {
    return parsedkey, nil
})
jwtValues = make(map[string]string)
// we dont know which data types we are dealing with here, so using swtich case based on value data type
jwtResp := parsedToken.Claims.(jwt.MapClaims)
    for k, v := range jwtResp {
        switch reflect.TypeOf(v).Kind() {

        case reflect.Slice:
            fmt.Println("tp is : ", reflect.TypeOf(v)) // this is []interface{}
            fmt.Println("type is : ", reflect.TypeOf(v).Kind()) // this is slice
            s := reflect.ValueOf(v)
            for i := 0; i < s.Len(); i++ {
                jwtValues[k] += s.Index(i).Interface().(string)
                jwtValues[k] += "|"
            }

        case reflect.String:
            jwtValues[k] = v.(string)

        default:
            fmt.Println("unknown datatype")
        }
    }

enter image description here

  • 写回答

2条回答 默认 最新

  • drxrgundk062317205 2017-05-02 16:34
    关注

    Thanks for the suggestions . Below is the closest solution i found replacing 'switch' with 'if' condition along with type assertions. 'reflect' is costly. Using below code, i am finding if values of jwtResp is a slice, or string or something else. If slice, traverse through the values([]interface with string type elements) and join those as one concatenated string.

    for k, v := range jwtResp {
            if s, ok := v.(string); ok {
                    JwtValues[k] = s
                } else if s, ok := v.([]interface{}); ok {
                    sslice := make([]string, len(s))
                    for i, v := range s {
                        sslice[i] = v.(string)
                    }
                    JwtValues[k] = strings.Join(sslice, "|")
                } else {
                    logger.Log(util.LogDebug, "unknown data type")
                }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。