简体   繁体   中英

golang : how to convert type interface {} to array

I have a JSON array with objects in Redis that I want to loop through it, but when I fetch the data, the type is interface{}, so I cannot range over type interface{}

array := redis.Do(ctx, "JSON.GET", "key")

arrayResult, e := array.Result()

if e != nil {
    log.Printf("could not get json with command  %s", e)
}

for _, i := range arrayResult {
    fmt.Printf(i)
}

I believe you should be able to do

for _, i := range arrayResult.([]byte) {
// do work here
}

Thank you guys, I found a solution. so at first I needed to convert the arrayResult to byte. Then I unmarshal it into a strcut, so now I am able to range over it.

array := redis.Do(ctx, "JSON.GET", "key")
arrayResult, e := array.Result()
if e != nil {
   log.Printf("could not get json with command  %s", e)
}

byteKey := []byte(fmt.Sprintf("%v", arrayResult.(interface{})))
RedisResult := struct{}
errUnmarshalRedisResult := json.Unmarshal(byteKey, &RedisResult)
if errUnmarshalRedisResult != nil {
       log.Printf("cannot Unmarshal msg %s", errUnmarshalRedisResult)
}

for _, i := range RedisResult {
   fmt.Printf(i)
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM