golang使用Gorm查询数据库并在http响应中返回json
问题描述:
我是Go新手,正在使用Gorm查询我的postgres数据库,但无法以字典格式返回我的数据,其中pokemon的类型作为该类型的所有口袋妖怪的数组golang使用Gorm查询数据库并在http响应中返回json
JSON:不能解组对象进式的围棋值[] models.Pokemon
这里是我的代码:
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)
esentially返回的*db
指针,你可以用它来进一步链方法返回的数据。 当您执行.Find(&retData.Poke)
时,您已经将postgre行反序列化到您的结构分区中。因此,pokemon
实际上并不是你想象的那样。
现在剩下的唯一东西是将.Find()
连接到.Error()
,以便您可以返回并检查查询中的任何错误。就像这样:
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.Poke中了 – user3226932