dongxing2263 2017-08-26 21:53
浏览 855
已采纳

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

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

json: cannot unmarshal object into Go value of type []models.Pokemon

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

{
  “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"},
  ]
}
  • 写回答

1条回答 默认 最新

  • douduan4116 2017-08-26 22:49
    关注

    DB.Where(&Pokemon{Type: t}).Find(&retData.Poke) esentially returns back the *db pointer which you can use to chain further methods. You're already deserializing postgre rows into your struct slice when you do .Find(&retData.Poke). Thus, pokemon isn't actually what you think it is.

    The only thing left now is to chain .Find() with a .Error() so that you can return and check any error in your query. 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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系