【发布时间】:2018-02-04 14:23:44
【问题描述】:
我是 Go 新手,我正在使用 Gorm 查询我的 postgres 数据库,但我无法以字典格式返回我的数据,其中 pokemon 的类型用作该类型所有 pokemon 数组的键
p>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"},
]
}
【问题讨论】:
标签: json postgresql go go-gorm