我在我的 postgres 数据库中存储了过程
SELECT *FROM get_products()
返回json
[
{
"id": 1,
"name": "one",
"addition": "spec1",
"size": "",
"category_id": 1,
"vendor_id": 1
},
{
"id": 2,
"name": "two",
"addition": "spec2",
"size": "",
"category_id": 1,
"vendor_id": 1
},
/// ...
]
如何在不创建结构的情况下从过程中返回结果,因为 json 中可能存在未知数量的字段?
我有这个代码。当过程返回表而不是json时,它运行良好
func (s ProductController) GetAll(c *gin.Context) {
db, err := sql.Open("postgres", "host=localhost dbname=postgres sslmode=disable user=postgres")
rows, err := db.Query("SELECT *FROM get_products()")
if err != nil {
panic(err)
}
cols, err := rows.Columns()
if err != nil {
panic(err)
}
allgeneric := make([]map[string]interface{}, 0)
colvals := make([]interface{}, len(cols))
for rows.Next() {
colassoc := make(map[string]interface{}, len(cols))
for i, _ := range colvals {
colvals[i] = new(interface{})
}
if err := rows.Scan(colvals...); err != nil {
panic(err)
}
for i, col := range cols {
colassoc[col] = *colvals[i].(*interface{})
}
allgeneric = append(allgeneric, colassoc)
}
err2 := rows.Close()
if err2 !=nil {
panic(err2)
}
fmt.Println(allgeneric)
c.JSON(200, allgeneric)
}
它返回这样的东西
[
{
"get_products": "W3siaWQiOjEsIm5hbWUiOiJHMTciLCJhZGRpdGlvbiI6IiIsInNpemUiOiJTdGFuZGFyZCIsImNhdGVnb3J5X2lkIjoxLCJ2ZW5kb3JfaWQiOjF9LCB7ImlkIjoyLCJuYW1lIjoiRzE3IiwiYWRkaXRpb24iOiJHZW40Iiwic2l6ZSI6IlN0YW5kYXJkIiwiY2F0ZWdvcnlfaWQiOjEsInZlbmRvcl9pZCI6MX0sIHsiaWQiOjMsIm5hbWUiOiJHMTciLCJhZGRpdGlvbiI6IkdlbjQgIiwic2l6ZSI6IlN0YW5kYXJkIiwiY2F0ZWdvcnlfaWQiOjEsInZlbmRvcl9pZCI6MX0sIHsiaWQiOjQsIm5hbWUiOiJHMTdDIiwiYWRkaXRpb24iOiJHZW40Iiwic2l6ZSI6IlN0YW5kYXJkIiwiY2F0ZWdvcnlfaWQiOjEsInZlbmRvcl9pZCI6MX0sIHsiaWQiOjUsIm5hbWUiOiJHMTciLCJhZGRpdGlvbiI6IkdlbjUiLCJzaXplIjoiU3
但我需要返回上面指定的 json
森栏
慕运维8079593
相关分类