来自https://blog.golang.org/json
解码任意数据
考虑以下 JSON 数据,存储在变量 b 中:
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
如果不知道数据的结构,我们可以通过Unmarshal将其解码为interface{}值:
var f interface{}
err := json.Unmarshal(b, &f)
此时f中的Go值将是一个映射,其键为字符串,其值本身存储为空接口值:
f = map[string]interface{}{
"Name": "Wednesday",
"Age": 6,
"Parents": []interface{}{
"Gomez",
"Morticia",
},
}
要访问这些数据,我们可以使用类型断言来访问 f 的底层 map[string]interface{}:
m := f.(map[string]interface{})
我们可以使用range语句遍历该映射,并使用类型开关访问其值作为它们的具体类型:
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case float64:
fmt.Println(k, "is float64", vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don't know how to handle")
}
}
以这种方式,您可以在仍然享受类型安全的好处的同时处理未知的JSON数据。