如何在Go中确定json对象的类型

问题描述:

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?

gobyexample中 .com / json 的一些示例,展示了如何将 json code>字符串解码为类型化的对象或字典对象,这些对象被声明为 map [string] interface {} code> 。 但它假设结果始终是字典。 p>

所以我的问题是如何确定 json code>对象的类型以及处理该对象的最佳实践是什么? p> div>

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.