2
我有一個config.json
以下格式:Golang JSON到地圖本身含有切片的地圖切片(不適用)
{
"recordType1": [
"field1", "field2", "field3", "field4", "field5"
],
"recordType2": [
"field1", "field2", "field3", "field4", "field5", "field6", "field7"
]
}
如果可能的話,我想將其轉換爲地圖切片,每個地圖本身就是一個「關鍵」,而「價值」則是一個切片。
我可以做到這一點手動喜歡:
package main
import ("fmt")
func main() {
m := make(map[string][]string, 0)
m2 := make(map[string][]string, 0)
sliceOfMaps := make([]map[string][]string, 0)
m["recordType1"] = []string{"field1", "field2", "field3"}
m2["recordType2"] = []string{"field1", "field2", "field3", "field4", "field5"}
sliceOfMaps = append(sliceOfMaps, m, m2)
fmt.Println(m)
fmt.Println(m2)
fmt.Println(sliceOfMaps)
}
相反,我想援引json.Unmarshal
上config.json
內容到JSON解析成非常相同的結構。
我試過到目前爲止:
package main
import (
"fmt"
"encoding/json"
"io/ioutil"
"log"
)
func main() {
file, err := ioutil.ReadFile("config/config.json")
if err != nil {
log.Fatal("Err Reading File:", err)
}
var sliceOfMaps []map[string][]string
sliceOfMaps = make([]map[string][]string, 0)
err = json.Unmarshal(file, &sliceOfMaps)
if err != nil {
log.Fatal("Err Parsing JSON", err)
}
fmt.Println(sliceOfMaps)
}
這會產生錯誤:
Err Parsing JSONjson: cannot unmarshal object into Go value of type []map[string][]string
任何幫助是極大的讚賞,澄清的問題表示歡迎。謝謝。