Simply decode and iterate to create the map.
func newEstadosMap() (estados map[string]string) {
raw := []byte(`{"estados":[{"sigla":"SP","nome":"São Paulo"},{"sigla":"RJ","nome":"Rio de Janeiro"}]}`)
dec := struct {
Estados []struct {
Sigla string `json:"sigla"`
Nome string `json:"nome"`
} `json:"estados"`
}{}
if err := json.Unmarshal(raw, &dec); err != nil {
return
}
estados = make(map[string]string)
for _, estado := range dec.Estados {
estados[estado.Sigla] = estado.Nome
}
return estados
}
First, we decode the json, for the struct dec. So we iterated on it, from dec.Estados to create the estados. I’ve put it all together into one function just to make it simpler, but you can break it into several functions...
Then you could do:
package main
import (
"encoding/json"
"fmt"
)
var Estados = newEstadosMap() // Invoca o código acima, criado o Estados assim que inicializar.
func main() {
fmt.Println(Estados["RJ"])
}
Upshot:
Rio de Janeiro