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
+7.3k Golang : Create S3 bucket with official aws-sdk-go package
+3.5k How to check with curl if my website or the asset is gzipped ?
+3k HTTP common errors and their meaning explained
+9.9k Golang : Normalize unicode strings for comparison purpose
+3.9k Javascript : Get operating system and browser information
+3.3k Golang : Return multiple values from function
+6.7k Golang : Terminate-stay-resident or daemonize your program?
+15.5k nginx: [emerg] unknown directive "passenger_enabled"
+6.1k Golang : Accept any number of function arguments with three dots(...)
+5.7k Golang : How to generate Code 39 barcode?
+14.3k Golang : Convert PNG transparent background image to JPG or JPEG image
+8.7k Golang : Pass database connection to function called from another package and HTTP Handler