dqy006150 2018-06-14 03:09
浏览 51

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

I had a Json of format

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

I want to create a Map that takes a tcp as key and add the tcID and time to it as a entry in a set.

I Want

[["/home/1.py"][{tcID,Time},{tcID,Time}],[["/home/2.py"][{tcID,Time},{tcID,Time}]]
  • 写回答

1条回答 默认 最新

  • dousuiguang9328 2018-06-14 07:22
    关注

    You can define a custom type, backed by a map, and then define a custom unmarshaller on that type.

    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
    } 
    

    You'll be able to access the elements like a regular map:

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

    Edited based on comment from OP to be map[string][]TCPValue

    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码