skip to Main Content

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)
}

2

Answers


  1. Chosen as BEST ANSWER

    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)
    } 
    

  2. I believe you should be able to do

    for _, i := range arrayResult.([]byte) {
    // do work here
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search