go - 在 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}]]
解决方案
您可以定义由映射支持的自定义类型,然后在该类型上定义自定义解组器。
// 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
推荐阅读
- android - 接收通知
- javascript - 当没有从提供者传递任何值时,为什么 react-context 返回未定义,而不是返回默认值?
- javascript - 如何在 JEST vue-test-utils 中模拟 $el 属性?
- html - 如何在文本悬停时将视频不透明度设置为线性渐变不透明度?
- mysql - 带有 MySql DB 的 Spring Boot JPA - 映射日期以错误的日期结束(休息 1 天)
- java - 时间格式最终在生产中发生变化
- python - Django NoReverseMatch 在 /create/
- android - 即使父活动处理onconfigurationchanged,如何强制片段重启
- perl - 如何在 Perl 中创建对子哈希成员值的引用?
- python - 计算一行中连续缺失值的数量