我有一個struct如下:
type TourData struct {
ArtistID int //artist ID
RelationID string //key for relations
City string
Country string
TourDates []string
}
type MyRelation struct {
ID int `json:"id"`
DatesLocations map[string][]string `json:"datesLocations"`
}
其中包含來自 csv 檔案的資料:
1,nagoya-japan,Nagoya,Japan,
1,penrose-new_zealand,Penrose,New_Zealand,
1,dunedin-new_zealand,Dunedin,New_Zealand,
2,playa_del_carmen-mexico,Playa Del Carmen,Mexico,
2,papeete-french_polynesia,Papeete,French_Polynesia,
MyRelations 由一個 API 填充,其中包含:
"index": [
{
"id": 1,
"datesLocations": {
"dunedin-new_zealand": [
"10-02-2020"
],
"nagoya-japan": [
"30-01-2019"
],
"penrose-new_zealand": [
"07-02-2020"
]
}
},
{
"id": 2,
"datesLocations": {
"papeete-french_polynesia": [
"16-11-2019"
],
"playa_del_carmen-mexico": [
"05-12-2019",
"06-12-2019",
"07-12-2019",
"08-12-2019",
"09-12-2019"
]
}
}
日期來自另一個結構。我用來填充這個結構的代碼如下:
var oneRecord TourData
var allRecords []TourData
for _, each := range csvData {
oneRecord.ArtistID, _ = strconv.Atoi(each[0])
oneRecord.RelationID = each[1]
oneRecord.City = each[2]
oneRecord.Country = each[3]
oneRecord.TourDates = Relations.Index[oneRecord.ArtistID-1].DatesLocations[each[1]]
allRecords = append(allRecords, oneRecord)
}
jsondata, err := json.Marshal(allRecords) // convert to JSON
json.Unmarshal(jsondata, &TourThings)
我需要將所有 1 組合在一起,然后將 2 等組合在一起。我想創建另一個結構,并從這個結構中填充,但運氣不佳 - 有什么想法嗎?
為了澄清,我想說 TourData.City 等于:
[Nagoya,Penrose,Dunedin]
[Playa Del Carmen, Papeete]
目前,如果我要列印 TourData[0].City,我會得到 Nagoya。
我嘗試使用以下欄位創建另一個從 TourData 結構填充的結構:
type TourDataArrays struct {
ArtistID int
City []string
Country []string
TourDates [][]string
}
然后使用以下代碼填充結構:
var tourRecord TourDataArrays
var tourRecords []TourDataArrays
for i := 0; i < len(Relations.Index); i {
for j := 0; j < len(allRecords); j {
if allRecords[i].ArtistID == i 1 {
tourRecord.City = append(tourRecord.City, allRecords[j].City)
}
}
tourRecords = append(tourRecords, tourRecord)
}
然而,這是將所有城市添加到一個陣列中,即
[名古屋、彭羅斯、達尼丁、普拉亞德爾卡門、帕皮提]。
uj5u.com熱心網友回復:
如果我正確理解您的要求,您還需要將 city 宣告為字串陣列。(和國家一起去)。
查看此解決方案:https ://go.dev/play/p/osgkbfWV3c5
請注意,我沒有從 Json 中的一個欄位中對國家/地區進行重復資料洗掉并派生出城市和國家/地區。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/438866.html
標籤:走
