go - 在 golang 中创建结构数组的映射?

标签 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}]]

最佳答案

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

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
} 

您将能够像普通 map 一样访问这些元素:

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

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

关于go - 在 golang 中创建结构数组的映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50849055/

相关文章:

java - 如何让 entrySet() 在新行显示键值对?(java)

php - PHP 数组是否需要在使用前声明?

bash - 关联数组 : error "declare: -A: invalid option"

go - Golang 上的包导入错误

java - Hashtable 与 HashMap 中的哈希函数?

java - Android - 将 Map<String, Object[]> 保存到文件

php - 如果它们具有相同的值,则打乱关联数组中键的顺序?

go - 使用结构解析 YAML

go - 在 C 共享库中公开一个带有 2D slice 作为参数的函数(通过 JNA 和 C 在 Java 中使用)

go - Golang 中 smtp 客户端的自定义拨号器?