php小編蘋果將為您介紹如何將一個Golang的map轉換成另一種map的結構。在開發過程中,有時我們需要對原有的map進行一些轉換操作,以滿足特定的需求。無論是資料類型的轉換還是結構的重新組織,都可以透過一些簡單的方法來實現。本文將為您詳細解析這個過程,幫助您快速掌握該技巧,提升開發效率。讓我們一起來探索這個有趣的轉換過程吧!
我需要協助將此輸入映射轉換為輸出映射。我嘗試使用 switch/case 和 for 但沒有成功。非常感謝!
輸入:
values{ "toto_voiture_brand": ad{ "citroen": "citroen", }, "toto_voiture_model": ad{ "citroen_toto": "c3", }, "toto_moto_brand": ad{ "kawasaki": "kawasaki", }, "toto_moto_model": ad{ "kawasaki_tata": "ninja 1000 sx", }, "toto_camion_brand": ad{ "renault": "renault", "peugeot": "peugeot", }, "toto_camion_model": ad{ "renault_toto": "j5", "peugeot_tata": "255", }, }, }
輸出
Values{ "toto_voiture_model": { "Citroen": { {Value: "C3"}, }, }, "toto_moto_model": { "Kawasaki": { {Value: "Ninja 1000 SX"}, }, }, "toto_camion_model": { "RENAULT": { {Value: "J5"}, }, "PEUGEOT": { {Value: "255"}, }, }, }
我嘗試過使用 switch case 和循環 for 和地圖。但我沒有結果參加者,我沒有找到如何匹配每個地圖、鍵和值。非常感謝
我應該使用以下程式碼來管理您所需要的內容:
package main import ( "encoding/json" "fmt" "strings" ) type Output struct { Value string `json:"Value"` } func main() { // declare output output := make(map[string]map[string]Output, 0) // input input := make(map[string]map[string]string, 0) input["toto_voiture_brand"] = map[string]string{ "CITROEN": "CITROEN", } input["toto_voiture_model"] = map[string]string{ "CITROEN_toto": "C3", } input["toto_moto_model"] = map[string]string{ "KAWASAKI_tata": "Ninja 1000 SX", } input["toto_camion_model"] = map[string]string{ "RENAULT_toto": "J5", "PEUGEOT_tata": "255", } // transformation for k, v := range input { if strings.HasSuffix(k, "_model") { tempMap := make(map[string]Output, len(v)) for kk, vv := range v { key := strings.Split(kk, "_")[0] tempMap[key] = Output{ Value: vv, } } output[k] = tempMap } } data, _ := json.MarshalIndent(&output, "", "\t") fmt.Println(string(data)) }
我在程式碼中加入了一些註釋,只是為了分隔各個部分。前兩部分僅用於定義輸入和輸出變數。
以 // conversion
開頭的部分是成為函數的良好候選者,但我更願意將其保留在 main
函數中以用於演示目的。讓我回顧一下 loop
中發生的事情:
input
變數的項目進行範圍_model
,則將其考慮在內tempmap
類型的本地範圍映射[string]output,其中包含我們要新增的正確數量的元素v
變數進行範圍調整(這就是我們處理巢狀映射的原因)tempmap
中新增一個條目output
)最後一部分只是列印一個漂亮的 json,可以輕鬆閱讀和檢查。
請注意,此程式碼經過簡化只是為了展示如何實現您的目標,請在投入生產之前對其進行調整。
請告訴我這是否有幫助,謝謝!
以上是將一個golang的map轉換成另一個map的結構的詳細內容。更多資訊請關注PHP中文網其他相關文章!