In gobyexample.com/json, a few examples show how to decode json
string into typed objects or dictionary objects, which are declared as map[string]interface{}
. But it assumes the result is always a dictionary.
So my question is how to determine the type of json
object and what is the best practice to handle that?
Checkout the definition of json.Unmarshal:
func Unmarshal(data []byte, v interface{}) error
So at least you can obtain the underlying type by using reflect.
var v interface{}
json.Unmarshal([]byte(JSON_STR), &v)
fmt.Println(reflect.TypeOf(v), reflect.ValueOf(v))
And switch
definitely is a better practice. I suppose below snippet
switch result := v.(type) {
case map[string]interface{}:
fmt.Println("dict:", result)
case []interface{}:
fmt.Println("list:", result)
default:
fmt.Println("value:", result)
}
can basically meet your requirement.