首页 > 解决方案 > 在 golang 中创建结构数组的映射?

问题描述

我有一个格式的 Json

{
    ...,
    "tclist":[{
        "tcID":"TC1",
        "tcp":"/home/1.py",
        "time":"20:00:40"
    }, {
        "tcID":"TC2",
        "tcp":"/home/1.py",
        "time":"048:50:06"
    }],
    ...
}

我想创建一个以 tcp 为键的 Map,并将 tcID 和时间作为集合中的一个条目添加到其中。

我想要

[["/home/1.py"][{tcID,Time},{tcID,Time}],[["/home/2.py"][{tcID,Time},{tcID,Time}]]

标签: gohashmapassociative-arraylinkedhashmaplinkedhashset

解决方案


您可以定义由映射支持的自定义类型,然后在该类型上定义自定义解组器。

这是 go playground 中的一个可运行示例

// the value in the map that you are unmarshalling to
type TCPValue struct {
    TcID string
    Time string
}

// the map type you are unmarshalling to
type TCPSet map[string][]TCPValue

// custom unmarshalling method that implements json.Unmarshaller interface
func (t *TCPSet) UnmarshalJSON(b []byte) error {
    // Create a local struct that mirrors the data being unmarshalled
    type tcEntry struct {
        TcID string `json:"tcID"`
        TCP string `json:"tcp"`
        Time string `json:"time"`
    }

    var entries []tcEntry

    // unmarshal the data into the slice
    if err := json.Unmarshal(b, &entries); err != nil {
        return err
    }

    tmp := make(TCPSet)

    // loop over the slice and create the map of entries
    for _, ent := range entries {
        tmp[ent.TCP] = append(tmp[ent.TCP], TCPValue{TcID: ent.TcID, Time: ent.Time})
    }

    // assign the tmp map to the type
    *t = tmp
    return nil
} 

您将能够像常规地图一样访问元素:

elem := tcpSet["/home/1.py"]

根据 OP 的评论进行编辑 map[string][]TCPValue


推荐阅读