代码之家  ›  专栏  ›  技术社区  ›  user3226932

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

  •  0
  • user3226932  · 技术社区  · 7 年前

    我是新手,正在使用Gorm查询我的postgres数据库,但在以字典格式返回数据时遇到了问题,在字典格式中,口袋妖怪的类型充当该类型所有口袋妖怪数组的键

    json:无法将对象解组为[]类型模型的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"},
      ]
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Mustansir Zia    7 年前

    DB.Where(&Pokemon{Type: t}).Find(&retData.Poke) E本质上返回 *db 可以用来链接其他方法的指针。 您已经在将postgre行反序列化到结构切片中了 .Find(&retData.Poke) pokemon 实际上并不是你想象的那样。

    现在只剩下锁链了 .Find() .Error() 这样您就可以返回并检查查询中的任何错误。就像这样:

    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
    }
    

    希望有帮助!