栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Golang 处理复杂格式JSON数据(多类型混合)

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Golang 处理复杂格式JSON数据(多类型混合)

补充

以下内容仅做学习参考,使用请使用以下网站获取相应返回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))
	}

参考:Go cannot range over (type interface {})"> (type interface {})" data-link-title="Go cannot range over (type interface {})">Go cannot range over (type interface {})

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/906965.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号