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
+10.5k Golang : Meaning of omitempty in struct's field tag
+7.6k Golang : Create zip/ePub file without compression(use Store algorithm)
+6.1k Javascript : Get operating system and browser information
+28.7k Golang : Read, Write(Create) and Delete Cookie example
+18.3k Golang : Get command line arguments
+8.2k Golang : Variadic function arguments sanity check example
+22.3k Golang : Securing password with salt
+19.3k Golang : Check if directory exist and create if does not exist
+21.9k SSL : How to check if current certificate is sha1 or sha2
+15.7k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+21.9k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+35.9k Golang : Smarter Error Handling with strings.Contains()