我有一个 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/