从通用且以某种方式动态的 go 地图获取内容的最佳方式是什么? [英] Whats the best way to get content from a generic and somehow dynamic go map?

查看:37
本文介绍了从通用且以某种方式动态的 go 地图获取内容的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个我转换成的 json:

I have this json that I convert to:

var leerCHAT []interface{}

但我正在经历疯狂的箍来到达地图内地图和地图内疯狂的地图上的任何点,特别是因为某些结果是不同的内容.这是Json

but I am going through crazy hoops to get to any point on that map inside map and inside map crazyness, specially because some results are different content. this is the Json

[
   null,
   null,
   "hub:zWXroom",
   "presence_diff",
   {
      "joins":{
         "f718a187-6e96-4d62-9c2d-67aedea00000":{
            "metas":[
               {
                  "context":{},
                  "permissions":{},
                  "phx_ref":"zNDwmfsome=",
                  "phx_ref_prev":"zDMbRTmsome=",
                  "presence":"lobby",
                  "profile":{},
                  "roles":{}
               }
            ]
         }
      },
      "leaves":{}
   }
]

我需要进入配置文件,然后里面有一个DisplayName".领域.

I need to get to profile then inside there is a "DisplayName" field.

所以我一直在做疯狂的黑客攻击......即使这样我也被卡在了一半......

so I been doing crazy hacks.. and even like this I got stuck half way...

First 是一个数组,所以我可以做一些事情[elementnumber]然后是棘手的映射开始的时候......抱歉,所有打印等都是为了调试并查看我返回的元素数量.

First is an array so I can just do something[elementnumber] then is when the tricky mapping starts... SORRY about all the prints etc is to debug and see the number of elements I am getting back.

if leerCHAT[3] == "presence_diff" {
                var id string
                presence := leerCHAT[4].(map[string]interface{})
                log.Printf("algo: %v", len(presence))
                log.Printf("algo: %s", presence["joins"])
                vamos := presence["joins"].(map[string]interface{})
                for i := range vamos {
                    log.Println(i)
                    id = i
                }
                log.Println(len(vamos))

                vamonos := vamos[id].(map[string]interface{})
                log.Println(vamonos)
                log.Println(len(vamonos))

                metas := vamonos["profile"].(map[string]interface{})   \ I get error here..

                log.Println(len(metas))
            }

到目前为止,我可以一直看到 meta:{...},但无法继续将我的 hacky 代码变成我需要的内容.

so far I can see all the way to the meta:{...} but can't continue with my hacky code into what I need.

注意:由于 Joins: 之后和 metas: 之前的 id 是动态的,我必须以某种方式获取它,因为它始终只是一个元素,我执行了 for range 循环来获取它.

NOTICE: that since the id after Joins: and before metas: is dynamic I have to get it somehow since is always just one element I did the for range loop to grab it.

推荐答案

索引 3 处的数组元素描述了索引 4 处的变体 JSON 的类型.

The array element at index 3 describes the type of the variant JSON at index 4.

以下是如何将 JSON 解码为 Go 值.首先,为 JSON 的每个变体部分声明 Go 类型:

Here's how to decode the JSON to Go values. First, declare Go types for each of the variant parts of the JSON:

type PrescenceDiff struct {
     Joins map[string]*Presence // declaration of Presence type to be supplied
     Leaves map[string]*Presence
}

type Message struct {
     Body string
}

声明一个将类型字符串关联到 Go 类型的映射:

Declare a map associating the type string to the Go type:

var messageTypes = map[string]reflect.Type{
    "presence_diff": reflect.TypeOf(&PresenceDiff{}),
    "message":       reflect.TypeOf(&Message{}),
    // add more types here as needed
}

将变体部分解码为原始消息.使用索引 3 处元素中的名称来创建适当 Go 类型的值并解码为该值:

Decode the variant part to a raw message. Use use the name in the element at index 3 to create a value of the appropriate Go type and decode to that value:

func decode(data []byte) (interface{}, error) {
    var messageType string
    var raw json.RawMessage
    v := []interface{}{nil, nil, nil, &messageType, &raw}
    err := json.Unmarshal(data, &v)
    if err != nil {
        return nil, err
    }

    if len(raw) == 0 {
        return nil, errors.New("no message")
    }

    t := messageTypes[messageType]
    if t == nil {
        return nil, fmt.Errorf("unknown message type: %q", messageType)
    }

    result := reflect.New(t.Elem()).Interface()
    err = json.Unmarshal(raw, result)
    return result, err
}

使用 类型开关 访问消息的变体部分:

Use type switches to access the variant part of the message:

defer ws.Close()

for {
    _, data, err := ws.ReadMessage()
    if err != nil {
        log.Printf("Read error: %v", err)
        break
    }

    v, err := decode(data)
    if err != nil {
        log.Printf("Decode error: %v", err)
        continue
    }

    switch v := v.(type) {
    case *PresenceDiff:
        fmt.Println(v.Joins, v.Leaves)
    case *Message:
        fmt.Println(v.Body)
    default:
        fmt.Printf("type %T not handled
", v)
    }
}

在操场上运行.

这篇关于从通用且以某种方式动态的 go 地图获取内容的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆