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

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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格