Use an interface whatever be the format you are getting from the json response and unmarshal the response into interface as:
func main(){
var result interface{}
if err := json.Unmarshal(jsonbytes, &result); err != nil{
fmt.Println(err)
}
}
Then use type assertion to fetch the value underlying the interface. But I think in your case if you do not the underlying type of a key. Better is to use recursion to fetch the value.
func fetchValue(value interface{}) {
switch value.(type) {
case string:
fmt.Printf("%v is an interface
", value)
case bool:
fmt.Printf("%v is bool
", value)
case float64:
fmt.Printf("%v is float64
", value)
case []interface{}:
fmt.Printf("%v is a slice of interface
", value)
for _, v := range value.([]interface{}) { // use type assertion to loop over []interface{}
fetchValue(v)
}
case map[string]interface{}:
fmt.Printf("%v is a map
", value)
for _, v := range value.(map[string]interface{}) { // use type assertion to loop over map[string]interface{}
fetchValue(v)
}
default:
fmt.Printf("%v is unknown
", value)
}
}
Working Code on Go playground
Above code will let you to fetch any type of value that is parsed into an interface.
Note:
In golang it is defined that when you unmarshal unknown json into an
interface. It will be converted into following types:
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays // slice of interface{}
map[string]interface{}, for JSON objects
nil for JSON null