dswqw66280
2018-11-16 17:38
浏览 130

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)
        }
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题