【问题标题】:Insert data in Go API using nested objects(structs)使用嵌套对象(结构)在 Go API 中插入数据
【发布时间】:2019-05-20 11:01:03
【问题描述】:

我正在创建一个 Golang API,但遇到了阻止程序。对于每个 POST,这就是我得到的: "error": "sql: converting argument $2 type: unsupported type main.Data, a struct"

我希望我的数据具有格式

        "name": "test",
        "other": {
            "age": "",
            "height": ""
        }
    }

我怎样才能做到这一点?请参阅下面的代码,到目前为止我已经尝试过。

model.go

type Data struct {
    ID   int    `json:"id"`
    Name string `json:"name,omitempty"`
    Other *Other `json:"other,omitempty"`
}

type Other struct {
    Age     string `json:"host,omitempty"`
    Height string `json:"database,omitempty"`
}

func (d *Data) Create(db *sql.DB) error {
    err := db.QueryRow(
        "INSERT INTO configs(name, other) VALUES($1, $2) RETURNING id",
        d.Name, &d.Other).Scan(&d.ID)
    if err != nil {
        return err
    }

    return nil
}

controller.go

...
func (a *App) createData(w http.ResponseWriter, r *http.Request) {
    var d Data
    decoder := json.NewDecoder(r.Body)

    if err := decoder.Decode(&d); err != nil {
        fmt.Print(err)
        fatalError(w, http.StatusBadRequest, "Invalid request")
        return
    }
    defer r.Body.Close()
    if err := d.Create(a.DB); err != nil {
        fatalError(w, http.StatusInternalServerError, err.Error())
        return
    }

    jsonResponse(w, http.StatusCreated, d)
}

我希望数据库中填充格式数据

        "name": "test",
        "other": {
            "age": "",
            "height": ""
        }
    }

但因错误而失败:

"error": "sql: converting argument $2 type: unsupported type main.Data, a struct"

【问题讨论】:

  • 扫描字符串中的其他 JSON。之后,您可以将其转换为 JSON。
  • 你能解释一下吗?
  • DB 驱动程序将每一列扫描为 []byte,然后默认将其转换为数据类型,它不会将 jsonb 的值扫描到结构中,要么您必须编写自定义扫描仪函数或读取string 和 json 中的列解组它。

标签: postgresql go mux


【解决方案1】:

您可以进行此修改:

import "encoding/json"

func (d *Data) Create(db *sql.DB) error {
   var jsonOther string
   if d.Other != nil {
      jsonOther, _ = json.Marshal(d.Other)
      err := db.QueryRow(
         "INSERT INTO configs(name, other) VALUES($1, $2) RETURNING id",
         d.Name, jsonOther).Scan(&d.ID)
      if err != nil {
          return err
      }
      return nil
 }

注意Other 对象被显式序列化为 JSON 并作为字符串传递

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2013-10-09
    • 2018-07-07
    相关资源
    最近更新 更多