Golang : Fix type interface{} has no field or no methods and type assertions example
For new comers to Golang exploring interface{}
for the first time or if you ever use interface{} to handle some arbitrary data, chances are that you will see this error message :
type interface {} has no field or method
or
type interface {} is interface with no methods
To fix this problem, you will need to convert the interface{} to a suitable type or extract the value(variable) with the explicit(correct)type from the interface{} with type assertions.
For example :
// convert the json objects from interface{} to []interface{}
// [] = slice/array type
var jsonObjs interface{}
json.Unmarshal([]byte(jsonStr), &jsonObjs)
objSlice, ok := jsonObjs.([]interface{})
or
// convert invoices to map[string]interface{}
for index, value := range invoices.(map[string]interface{}) {
fmt.Println(index, value)
}
Hope this helps!
References :
https://www.socketloop.com/tutorials/golang-count-json-objects-and-convert-to-slice-array
See also : Golang : Count JSON objects and convert to slice/array
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.7k Golang : Error reading timestamp with GORM or SQL driver
+27.2k Golang : Find files by name - cross platform example
+6.2k Golang : Process non-XML/JSON formatted ASCII text file example
+14.7k Golang : Get URI segments by number and assign as variable example
+14.2k Golang : Convert IP version 6 address to integer or decimal number
+11.9k Golang : Convert(cast) bigint to string
+20.2k Golang : Compare floating-point numbers
+6.8k Default cipher that OpenSSL used to encrypt a PEM file
+14.1k Golang : Check if a file exist or not
+5.7k Fix yum-complete-transaction error
+6.9k Nginx : Password protect a directory/folder