dti70601 2015-05-10 10:05
浏览 441

使用Redigo将JSON部分从Redis转换为Go结构

I have a json that is POSTed by a browser. It's a hash with

var id int64 = 123 

and, say, three fields like so:

myJson := `{ 
    "a":"{'x1':'apple','x2':'orange'}", 
    "b":"{'y1':345678,'y2':32456}", 
    "c":"['alpha@example1.com', 'beta@example2.com']"}`

It's then stored in Redis using redigo with command:

HMSET id:123 a "{'x1':'apple','x2':'orange'}" b "{'y1':345678,'y2':32456}" c "['alpha@example1.com', 'beta@example2.com']"

Now, I'd like to use a model like this in Go

type Model struct {
    A string `json:"a"`
    B string `json:"b"`
    C string `json:"c"` // Unknown length of map at runtime
}

1. I call Redis with

v, _ := redis.Values(c.Do("HGETALL", "id:123"))

I see correctly stored values via redis-cli, but converting the v reply into the Model struct doesn't work:

var model Model
if err := redis.ScanStruct(v, &model); err != nil {
    panic(err)
}
fmt.Printf("c %#v
", model.C) => empty []

I'd like to access individual k:v pairs like:

B.y2 = 32456
C[0] = "alpha@example1.com"

2. I'd also like to json.Marshal myJson back to the browser as combinations of {a}, {a,b}, {a,c}, {a,b,c}, etc. I'm not sure how to combine various a,b,c field combos into one to be Marshalled.

Any help would be appreciated.

  • 写回答

3条回答 默认 最新

  • doulianxing4015 2015-05-10 10:47
    关注

    First of all, you should tag your field names with redis and not json tags, that's what redigo uses for ScanStruct(). e.g

    type Model struct {
        A string `redis:"a"`
        B string `redis:"b"`
        C string `redis:"c"` // Unknown length of map at runtime
    }
    

    Second, your members are strings, so you can't have individual member access to their content, and I don't think you can automate it with redigo.

    You can, as workaround have some type that extends string, and has an access method that lazily parses the json into an underlying dict and then returns the value. Something like this (writing without testing, just the general idea, I'm not sure it will work but it's worth a try):

    type MyString string
    
    func (s MyString)Get(key string) (interface{}, error) {
       var m map[string]interface{}
    
       if err := json.Unmarshal([]byte(s), &m); err != nil {
           return nil, err
       } 
    
       return m[key], nil
    
    }
    

    It's also not very efficient as it will parse the json again each time. Personally I'd wrap this whole model thing in a struct that does all that logic behind the scene while deserializing from redigo.

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)