在golang中创建一个结构数组的映射?

时间:2018-06-14 03:09:27

标签: go hashmap associative-array linkedhashmap linkedhashset

我有格式的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}]]

1 个答案:

答案 0 :(得分:1)

您可以定义由地图支持的自定义类型,然后在该类型上定义自定义unmarshaller。

Here is a runnable example in the 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