0
我是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"},
]
}
謝謝你!原來我也不需要編組/解組了,因爲數據已經在retData.Poke中了 – user3226932