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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了