dswqw66280 2018-11-16 17:38
浏览 143
已采纳

GoLang Redis:地图和切片

I'm using GoLang to get a data from redis hash and then map into a struct.

type Person struct {
    ID         string       `json:"id"`
    FirstName  string       `json:"firstName"`
    LastName   string       `json:"lastName"`
    Filters    interface{}  `json:"filters"`
    Type       string       `json:"type"`
}

In Redis, a hash field contains a stringified JSON.

HGET hashname fieldname

Above returns a stringified JSON.

Now "filters" key can be array or map based on the type (That's why I defined Filters type as interface in struct).
I marshall the JSON like below:

var p Person
content, err := redis.HGet("hashName", "id").Result()
_ = json.Unmarshal([]byte(content), &p)

Now I have to loop over filters like below but this is giving error that cannot range over p.Filters (type interface {}) (I understand why this error is coming)

for _, filter := range p.Filters {
  fmt.Println(filter)
}

Is there any way we can handle this situation?

Thanks,
Shashank

  • 写回答

1条回答 默认 最新

  • dongqiao3927 2018-11-16 17:44
    关注

    You need to convert Filters type interface{} into the expected slice. If you don't really know what type it will be, you can use map[string]interface{}. Therefore change your Filters type to map[string]interface{}.

    Per more information If Filters can be an array (or not), then you might consider a type switch:

    A simple example:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        var i interface{}
        //json.Unmarshal([]byte(`["hi"]`), &i)
        json.Unmarshal([]byte(`{"a":"hi"}`), &i)
    
        switch i.(type) {
        case []interface{}:
            println("ARRAY")
        case map[string]interface{}:
            println("NOT ARRAY")
        default:
            fmt.Printf("%T
    ", i)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?