我有一个场景,我向第三方 API 发送请求,提供如下响应:
data: [
{
id: 111,
highPriorityItems: [
{
"time": "2022-01-01T00:00:50Z",
"price": 5000.55
},
{
"time": "2022-01-02T13:00:50Z",
"price": 5600.55
},
...
],
lowPriorityItems: [
{
"time": "2022-03-01T00:12:50Z",
"price": 9000.55
},
{
"time": "2022-03-02T22:00:50Z",
"price": 6700.55
},
...
]
},
...
]
lowPriorityItems
总是在那里,而highPriorityItems
并不总是在那里。我想要的结果是使用highPriorityItems
(如果存在)并捕获该数据。
棘手的部分是 API 是分页的,可以返回许多带有这些嵌入式 priorityItem 数组的单独对象,这意味着一个响应可能只显示特定
lowPriorityItems
的 id
,而下一个分页响应可能显示 highPriorityItems
相同的 id
. 数组
我想得到一个最终结果,我只有 ID 和
lowPriorityItems
和 highPriorityItems
切片在一个 struct
中。如果 highPriorityItems
是空的,我可以在结果中并排放置两个切片后选择使用 lowPriorityItems
。
试图想出一种简洁有效的方法来处理这个想法。目前的想法:
package main
type Payload struct {
Data []Entity `json:"data"`
}
type Entity struct {
Id string `json:"id"`
HighPriorityItems []Item `json:"highPriorityItems"`
LowPriorityItems []Item `json:"lowPriorityItems"`
}
type Item struct {
time string
price float64
}
func main() {
payloads := []&Payload{}
for _, req := requests {
// Boilerplate to unmarshal response into Payload struct and append to our slice of Payloads
// Each response gets appended to our slice of payloads
payloads = append(payloads, payload)
}
// Here is where I am thinking that I need logic to essentially check if I have already
// Received a payload that has an object with the Id of the paginated payload, and if it does, append to our ```Entity``` priorityItem slices for that specific idea (so I can maintain a complete collection of both item types for the same ```id```
// Does it make sense to each time loop over my current payload list and check for Ids (seems expensive) or maybe utilize another data structure (map w/ structs?) in some way?
}
在由 id 键控的实体映射中记录项目:
entities := make(map[string]*Entity)
对于每个响应,遍历实体。如果第一个实体将实体添加到地图,否则将项目附加到第一个实体。
for i := range resp.Data {
e := &p.Data[i]
if me, ok := entities[e.Id]; !ok {
entities[e.Id] = me
} else {
me.LowPriorityItems = append(me.LowPriorityItems, e.LowPriorityItems...)
me.HighPriorityItems = append(me.HighPriorityItems, e.HighPriorityItems...)
}
}
遍历地图值以访问实体:
for _, e := range entities {
// do something with e
}