简体   繁体   English

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

[英]golang querying database using Gorm and returning json in http response

I'm new to Go and am using Gorm to query my postgres database but am having trouble returning my data in a dictionary format, where the pokemon's type serves as a key to an array of all the pokemon of that type 我是Go的新手,正在使用Gorm查询我的postgres数据库,但是在以字典格式返回数据时遇到了麻烦,其中,神奇宝贝的类型用作所有该类型神奇宝贝的数组的键

json: cannot unmarshal object into Go value of type []models.Pokemon json:无法将对象解组为[] models.Pokemon类型的Go值

here's my code: 这是我的代码:

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

I have this in my database 我的数据库中有这个

name       | type
----------------------
pikachu    | electric
charmander | fire
blaziken   | fire
venusaur   | grass
treeko     | grass
squirtle   | water

I want to return data in this json format 我想以这种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 returns back the *db pointer which you can use to chain further methods. DB.Where(&Pokemon{Type: t}).Find(&retData.Poke)返回*db指针,您可以使用该指针来链接其他方法。 You're already deserializing postgre rows into your struct slice when you do .Find(&retData.Poke) . 当您执行.Find(&retData.Poke)时,您已经将Postgre行反序列化到结构切片中。 Thus, pokemon isn't actually what you think it is. 因此, pokemon实际上并不是您想的那样。

The only thing left now is to chain .Find() with a .Error() so that you can return and check any error in your query. 现在剩下的唯一事情是将.Find().Error()以便您可以返回并检查查询中的任何错误。 Just like this : 像这样 :

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
}

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM