如何使用Golang创建Nest JSON数组对象



我尝试查询数据库并使用查询结果来创建像这些

的JSON

[{" transid":" TransAction ID1",productid':[" proid1"," proid2"," proid3"," proid4"]},

{" transid":"事务id2"," productid":[" proid5"," proid6"]}]

所以我从

中创建类型结构
type DataRecent []struct {
 TransID   string   `json:"transID"`
 ProductID []string `json:"productID"`}

和Golang代码是

var dataRecent DataRecent
var recent [5]string
for _, Trans := range recent {
    if Trans != "" {
        var TransID, ProductID string
        selectTrans, err := db.Query("select transaction_id, product_id from detail where transaction_id = ?", Trans)
        var arr []string
        for selectTrans.Next() {
            if err != nil {
                panic(err.Error())
            }
            errTrans := selectTrans.Scan(&TransID, &ProductID)
            if errTrans != nil {
                panic(errTrans.Error())
            }
            arr = append(arr, ProductID)
        }
    }
        dataRecent.TransID = Trans
        dataRecent.ProductID = arr
}
    c.JSON(http.StatusOK, gin.H{"status": "success", "message": "Find transactions success", "recent_trans": dataRecent})

defer db.Close()

,但我无法构建代码并有错误

datarecent.transid不确定(type dataRecent没有字段或方法transid) datarecent.productid undewined(类型dataRecent没有字段或方法ProduciD)

我不知道该怎么办,并且坚持了一个星期。我是Golang的新程序员。帮助我pleae,谢谢

创建struct

时只需删除数组
type DataRecent struct {
 TransID   string   `json:"transID"`
 ProductID []string `json:"productID"`
}

和做

var dataRecent []DataRecent

它将对您有用。

看起来DataRecent并未初始化。我建议您使用dataRecent := DataRecent{}代替var dataRecent DataRecent

其他一些见解:我不确定您是否省略了最近字符串数组的make的用法,或者您不知道需要make()。无论如何,数组是GO中的值,如果您是新手,我强烈建议您使用切片。https://blog.golang.org/go-slices-usage-and-internals

另外,我不确定您为什么要 panic(),以防您找到错误(用戴夫·切尼(Dave Cheney)的话, panic的意思是"男人的游戏" - https://dave.cheney.net/tag/panic)

最新更新