golang使用Gorm查询数据库并在http响应中返回json

golang使用Gorm查询数据库并在http响应中返回json,json,postgresql,go,go-gorm,Json,Postgresql,Go,Go Gorm,我是新手,正在使用Gorm查询我的postgres数据库,但在以字典格式返回数据时遇到了问题,因为口袋妖怪的类型是该类型所有口袋妖怪数组的键 json:无法将对象解组为[]models.Pokemon类型的Go值 这是我的密码: type Pokemon struct { Name string `db:"name"` Type string `db:"type"` } pokemonTypes := [6]string{ "fire", "el

我是新手,正在使用Gorm查询我的postgres数据库,但在以字典格式返回数据时遇到了问题,因为口袋妖怪的类型是该类型所有口袋妖怪数组的键

json:无法将对象解组为[]models.Pokemon类型的Go值

这是我的密码:

type Pokemon struct {
    Name   string   `db:"name"`
    Type   string   `db:"type"`
}

pokemonTypes := [6]string{
    "fire",
    "electric",
    "water",
    "grass",
}

var retData struct {
   Poke []Pokemon
}

m := make(map[string][]Pokemon)

for _, t := range pokemonTypes {
    pokemon := DB.Where(&Pokemon{Type: t}).Find(&retData.Poke)
    p, _ := json.Marshal(pokemon)
    err = json.Unmarshal(p, &retData.Poke)  // getting error here
    if err != nil {
        fmt.Println(err)
    }
    m[category] = retData.Poke
}

data, _ := json.Marshal(m) 
w.Write(data)  // http repsonse
我的数据库里有这个

name       | type
----------------------
pikachu    | electric
charmander | fire
blaziken   | fire
venusaur   | grass
treeko     | grass
squirtle   | water
我想以这种json格式返回数据

{
  “electric”: [
    {"name": "pikachu", "type": "electric"},
  ],
  "fire": [
    {"name": "charmander", "type": "fire"},
    {"name": "blaziken", "type": "fire"}
  ],
  "grass": [
    {"name": "venusaur", "type": "grass"},
    {"name": "treeko", "type": "grass"},
  ],
  "water": [
    {"name": "squirtle", "type": "water"},
  ]
}
DB.Where(&Pokemon{Type:t}).Find(&retData.Poke)
本质上返回
*DB
指针,您可以使用该指针链接其他方法。 在执行
.Find(&retData.Poke)
时,您已经在将postgre行反序列化到结构切片中。因此,
pokemon
实际上并不是你想象的那样

现在唯一剩下的就是用
.Error()
链接
.Find()
,这样您就可以返回并检查查询中的任何错误。就这样,

for _, t := range pokemonTypes {
    err := DB.Where(&Pokemon{Type: t}).Find(&retData.Poke).Error()
    if err != nil {
        fmt.Println(err)
        return
    }
    p, _ := json.Marshal(retData.Poke)
    err = json.Unmarshal(p, &retData.Poke) 
    if err != nil {
        fmt.Println(err)
        return
    }
    m[category] = retData.Poke
}
希望有帮助

DB.Where(&Pokemon{Type:t}).Find(&retData.Poke)
本质上返回
*DB
指针,您可以使用该指针链接其他方法。 在执行
.Find(&retData.Poke)
时,您已经在将postgre行反序列化到结构切片中。因此,
pokemon
实际上并不是你想象的那样

现在唯一剩下的就是用
.Error()
链接
.Find()
,这样您就可以返回并检查查询中的任何错误。就这样,

for _, t := range pokemonTypes {
    err := DB.Where(&Pokemon{Type: t}).Find(&retData.Poke).Error()
    if err != nil {
        fmt.Println(err)
        return
    }
    p, _ := json.Marshal(retData.Poke)
    err = json.Unmarshal(p, &retData.Poke) 
    if err != nil {
        fmt.Println(err)
        return
    }
    m[category] = retData.Poke
}

希望有帮助

谢谢你,伙计!原来我也不需要封送/解封,因为数据在retData中!事实证明,我不需要封送/解封,因为数据已经在retData.Poke中了