我正在json.Decode()把一个json响应从一个api转换成一个大的结构体。在这个结构体里有几个[]interface{}类型的类型。我想不出如何从那些特殊的嵌套结构体中提取任何数据。我尝试过使用case switch类型检查解决方案,但仍然一无所获。有没有人可以分享他们的经验,或者给我指出正确的方向?
m := new(largestruct)
if err := json.NewDecoder(resp.Body).Decode(&m); err != nil{
return err
}接口的struct字段为:
Strings []interface{} `json:"strings"`发布于 2018-08-06 23:56:47
使用switch case,您可以获取接口底层的值。该函数将以递归方式运行,直到获得解析的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中定义,其中清楚地描述了当使用接口{}解组时,json将解析成什么值:
要将JSON解组为接口值,unmarshal会在接口值中存储以下内容之一:
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 nullhttps://stackoverflow.com/questions/51711154
复制相似问题