我是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"},
]
}