Reputation: 328
I'm confused how to use YAML MapSlice data Structure. It's from here https://sourcegraph.com/go/gopkg.in/yaml.v2/-/MapSlice . I manage to unmarshall to a type of MapSlice but how to map it to my own struct
var data = `
id:
id-jakut:
en:
name: North Jakarta City
label: North Jakarta
id:
name: Kota Jakarta Utara
label: Jakarta Utara
id-jaksel:
en:
name: South Jakarta City
label: South Jakarta
id:
name: Kota Jakarta Selatan
label: Jakarta Selatan
tw:
tw-tp:
en:
name: Taipei City
label: Taipei
zh-TW:
name: 台北
label: 台北市
tw-ntp:
en:
name: New Taipei City
label: New Taipei City
zh-TW:
name: 新北市
label: 新北市
`
type cityLocale struct {
Name string `yaml:"name,flow"`
Label string `yaml:"label,flow"`
}
type cityLocales map[string]cityLocale
type cities map[string]cityLocales
type countryCities map[string]cities
func main() {
m := yaml.MapSlice{}
err := yaml.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("MAPSLICE==>%+v\n\n", m)
t := countryCities{}
err = yaml.Unmarshal([]byte(data), &t)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("NORMAL==>%+v\n", t["tw"])
}
Upvotes: 0
Views: 2982
Reputation: 1427
You can convert the MapSlice to your own type. This involves type conversion. Especially for nested types like you have in your example.
I've given a very basic example in another answer you can find here.
Upvotes: 0
Reputation: 5894
You need to change your cities type, because you missed one map. If your cities are a map of map of strings your code works:
type cities map[string]map[string]cityLocales
Upvotes: 1