【问题标题】:How to use golang create nest json array object如何使用golang创建嵌套json数组对象
【发布时间】:2019-03-04 11:42:11
【问题描述】:

我尝试查询数据库并使用查询结果来创建像这样的 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 未定义(DataRecent 类型没有字段或方法 TransID) dataRecent.ProductID 未定义(DataRecent 类型没有 ProductID 字段或方法)

我不知道该怎么办,坚持了一周。我是 golang 的新程序员。请帮帮我,谢谢

【问题讨论】:

    标签: go go-gin


    【解决方案1】:

    创建结构时删除数组

    type DataRecent struct {
     TransID   string   `json:"transID"`
     ProductID []string `json:"productID"`
    }
    

    然后做

    var dataRecent []DataRecent
    

    它会为你工作。

    【讨论】:

      【解决方案2】:

      看起来 dataRecent 没有初始化。我建议你使用dataRecent := DataRecent{} 而不是var dataRecent DataRecent

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

      另外,我不知道为什么你必须panic() 以防你发现错误(用 Dave Cheney 的话来说,panic 的意思是“人的游戏” - https://dave.cheney.net/tag/panic

      【讨论】:

        猜你喜欢
        • 2018-11-27
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 2023-02-17
        • 1970-01-01
        • 2016-09-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多