douhao7889 2019-03-04 11:42
浏览 309

如何使用golang创建嵌套的json数组对象

I try to query database and use query result to create json like these

[ {"TransID": "Transaction ID1",ProductID": ["ProID1","ProID2","ProID3","ProID4" ]},

{"TransID": "Transaction ID2","ProductID": ["ProID5","ProID6" ]} ]

so I create type struct from

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

and golang code is

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()

but I can't build the code and got error

dataRecent.TransID undefined (type DataRecent has no field or method TransID) dataRecent.ProductID undefined (type DataRecent has no field or method ProductID)

I don't know what to do and stuck with these for a week. I am new programmer for golang. Help me pleae, Thank you

  • 写回答

2条回答 默认 最新

  • douweicheng5532 2019-03-04 11:48
    关注

    Just remove the array when you create the struct

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

    and do

    var dataRecent []DataRecent
    

    it will works for you.

    评论

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果