Yaml MapSlice to preserve the sequence when marshall or unmarshall
Im confused how to use Yaml MapSlice data Structure. its 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"])
}
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