补充

以下内容仅做学习参考,使用请使用以下网站获取相应返回JSON结构体:JSON 转 Golang Struct

起因 

在调取百度人体检测接口时,返回的JSON数据嵌套了多层,解析为map[string]interface()类型的数据后,在遍历取值过程中出现了一些异常,如下两个等:

cannot range over person_info (type interface {})

interface conversion: interface {} is []interface {}, not map[string]interface {}

原始数据

以下为返回的JSON数据

{
    "person_num": 2,
    "person_info": [
        {
            "attributes": {
                "orientation": {
                    "score": 0.9992424249649048,
                    "name": "正面"
                },
                "gender": {
                    "score": 0.9216505289077759,
                    "name": "男性"
                }
            },
            "location": {
                "score": 0.9567705988883972,
                "top": 327,
                "left": 283,
                "width": 133,
                "height": 152
            }
        },
        {
            "attributes": {
                "orientation": {
                    "score": 0.9960677623748779,
                    "name": "正面"
                },
                "gender": {
                    "score": 0.9766052961349487,
                    "name": "女性"
                }
            },
            "location": {
                "score": 0.9070568680763245,
                "top": 339,
                "left": 488,
                "width": 90,
                "height": 139
            }
        }
    ],
    "log_id": 1471750893281891840
}
处理方式

在处理返回的JSON数据时,Golang需要用特定的数据类型去承接JSON的数据类型,具体如下:

序号JSON 数据类型Golang 数据类型
1booleansbool
2numbersfloat64
3stringsstring
4arrays[]interface{}
5objectsmap[string]interface{}
6nullnil

代码

以下为处理上面原始数据的一段示例,在原始数据中:person_num为numbers类型数据,所以转为float64;person_info为arrays类型,所以转为[]interface{}类型进行处理

	person_num := person["person_num"].(float64)

	person_info := person["person_info"].([]interface{})
	for _, val := range person_info {
		fmt.Println(reflect.TypeOf(val))
	}