When I have a reliable rest api endpoint that returns some simple json, I can use a struct to define exactly the structure of the expected json result, but there are certain endpoints I have to use that return very large and complex json result data, and the structure of these results are not always known.
I have been using this to unmarshal into:
type JsonObj map[string]interface{}
func (jo JsonObj) GetString(name string) (string, error) {
if val, exists := jo[name]; exists {
if v, ok := val.(string); ok {
return v, nil
}
return "", errors.New(name+" is not a string")
}
return "", errors.New(name+" property not found")
}
func (jo JsonObj) GetFloat64(name string) (float64, error) {
if val, exists := jo[name]; exists {
if v, ok := val.(float64); ok {
return v, nil
}
return 0, errors.New(name+" is not a float64")
}
return 0, errors.New(name+" property not found")
}
and in this same way I have GetInt
, GetBool
, GetSlice
, GetJsonObj
,
but as you can see all of these functions are virtually identical in content except for the type assertion parameter. is there a way of passing in the type assertion parameter to reduce all these functions effectively to a single function?