Golang : [json: cannot unmarshal object into Go value of type]
Un-marshalling JSON data from external sources can be challenging sometimes. Encountered this error message while working on the previous tutorial to display list of countries and the ISO2 codes.
json: cannot unmarshal object into Go value of type
Apparently, it was because the JSON data given by country.io has no fields identifiers. Only iso codes follow by country names. For instance :
{"BD": "Bangladesh", "BE": "Belgium" }
To deal(un-marshal) with this kind of data. First, we need to define a map expecting string and with the help of interface{}
For example,
resp, err := http.Get("http://country.io/names.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer resp.Body.Close()
jsonCountriesData, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
countriesMap := make(map[string]interface{})
// Decode JSON into our map
err = json.Unmarshal([]byte(jsonCountriesData), &countriesMap)
if err != nil {
println(err)
return
}
See for full source code example at : https://www.socketloop.com/tutorials/golang-display-list-of-countries-and-iso-codes
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.6k Elasticsearch : Shutdown a local node
+6.8k Golang : Error reading timestamp with GORM or SQL driver
+44.1k Golang : Read tab delimited file with encoding/csv package
+8.6k Golang : How to check if a website is served via HTTPS
+5.1k Golang : Extract XML attribute data with attr field tag example
+10.1k Use systeminfo to find out installed Windows Hotfix(s) or updates
+3.8k Linux : How to set root password in Linux Mint
+18.3k Golang : Determine if directory is empty with os.File.Readdir() function
+21.1k Golang : How to read JPG(JPEG), GIF and PNG files ?
+6.8k Golang : Check from web if Go application is running or not
+12.5k Golang : Compress and decompress file with compress/flate example
+10.6k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example