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
+15.1k Golang : Get all upper case or lower case characters from string example
+9.4k Golang : Determine if time variables have same calendar day
+5.9k Prevent Write failed: Broken pipe problem during ssh session with screen command
+4k Fix yum-complete-transaction error
+4.7k Golang : How to detect if a sentence ends with a punctuation?
+12.4k Golang : How to get Unix file descriptor for console and file
+13k Golang : Read large file with bufio.Scanner cause token too long error
+4.3k Golang : List all packages and search for certain package
+6.3k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+6.7k Golang : Convert(cast) []byte to io.Reader type
+4.8k Unix/Linux : How to get own IP address ?
+11.8k Golang : GUI with Qt and OpenCV to capture image from camera