【Golang报错】100% 解决 json: cannot unmarshal array into Go value of type model.xxx 问题

背景:

在 go 项目中,查询数据时,获取不到数据。请求失败。

根据 go 项目的日志,获得如下报错信息。

报错信息:

2023/03/06 20:54:40 [31;1m/xxxx/task.go:476 [35;1msql: Scan error on column index 3, name "xxx": json: cannot unmarshal array into Go value of type model.xxxx
[0m[33m[31.874ms] [34;1m[rows:1][0m SELECT * FROM "xxx" WHERE TID='xxx' ORDER BY "xxx"."id" LIMIT 1

解决方案:

检查定义的类型是否有问题:

type Results map[string]interface{} --》type Results []map[string]interface{}

黑色修改为红色。

原因:

在定义的 model 中,某一个字段的数据类型应该定义为:

type Results map[string]interface{}

但其实数据库中存储的类型与此不符合。

在数据库中存储的是 数据嵌套的字典,转换的 JSON 格式。

现在要反序列化传给前端,所以应该改成如下:

type Results []map[string]interface{}

号外号外:)

我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=294utw6ouxhcg

猜你喜欢

转载自blog.csdn.net/Mercury_Lc/article/details/129371019
今日推荐