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

报告相同问题?

悬赏问题

  • ¥50 unitywebrequest分段下载导致报错,如何解决?
  • ¥15 错误使用 gretna_GUI_PreprocessInterface>RunBtn_Callback
  • ¥15 WPF如何用Chart绘画出Y轴的左边数据
  • ¥15 pycharm无法查看内置代码
  • ¥15 跑hls xfopencv的例程standalone_hls_axi_example出的错误,csim没问题,c synthesis出的错误
  • ¥15 sqlserver update语句逐行生效
  • ¥20 Windows10系统命令行调用
  • ¥15 php环境如何实现国密SM2相关功能
  • ¥15 关于#单片机#的问题:K210 例程里面提示我iomem.h: No such file or directory
  • ¥15 LSPI算法的大问题