我正在将 json.Decode()'ing(请原谅我的速记)从 api 到大型结构的 json 响应。在该结构中有一些属于 []interface{} 类型的类型。我不知道如何从那些特殊的嵌套结构中提取任何数据。我曾尝试使用 case switch 类型检查解决方案,但仍然空手而归。有人可以分享他们在类似案例中的经验或为我指明正确的方向吗?
m := new(largestruct)
if err := json.NewDecoder(resp.Body).Decode(&m); err != nil{
return err
}
接口(interface)的结构字段是:
Strings []interface{} `json:"strings"`
最佳答案
使用 switch case 你可以获取接口(interface)下的值。该函数将递归运行,直到它获取到解析后的 json 的原始类型。
func fetchValue(value interface{}) { // pass the interface value from the struct in this function as it will run recursively to get the value.
switch value.(type) {
case string:
fmt.Printf("%v is an string \n ", value.(string))
case bool:
fmt.Printf("%v is bool \n ", value.(bool))
case float64:
fmt.Printf("%v is float64 \n ", value.(float64))
case []interface{}:
fmt.Printf("%v is a slice of interface \n ", value)
for _, v := range value.([]interface{}) {
fetchValue(v)
}
case map[string]interface{}:
fmt.Printf("%v is a map \n ", value)
for _, v := range value.(map[string]interface{}) {
fetchValue(v)
}
default:
fmt.Printf("%v is unknown \n ", value)
}
}
开关类型受限的原因在 golang spec for unmarshal 中定义。其中清楚地描述了在使用 interface{} 解码时 json 将解析成什么值:
To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
关于go - 我如何在 Go 中对接口(interface) slice 进行 json 解码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51711154/