Gorm输出到json

时间:2014-11-25 18:10:48

标签: json go gorp

我正在尝试将SQL输出(GORP)转换为JSON。我正在使用gorp和mySql。

这是我选择的代码

type Mane struct {
    ManeId   string `db:"mane_id"`
    Manetana string `db:"manetana"`
    Yajamana string `db:"yajamana"`
}

var manegalu []Mane
_, err = dbmap.Select(&manegalu, "SELECT mane_id, manetana, yajamana FROM kd_mane")

//Option 1: Not working: Array of numbers. Not the actual json
a, err := json.Marshal(manegalu)
mt.Fprint(w, string(a))

//Option 2: Not working: Array of numbers. Not the actual json
for _, p := range manegalu {
    a, err := json.Marshal(p)
    fmt.Fprint(w, string(a))
}

我期待并像这样输出

{"mane_id":3323, "manetana":"ABC", "yajamana":"hgy"},{"mane_id":2323, "manetana":"ADFC", "yajamana":"FDER"},{"mane_id":12343, "manetana":"GDSC", "yajamana":"hFDEy"} 
你能告诉我我做错了什么吗?我理解为什么选项1不起作用。但根据https://gobyexample.com/json

,选项2对我来说似乎不错

2 个答案:

答案 0 :(得分:2)

json.Marshal()会返回两个值,[]byteerror。您只是在示例中指定了第一个。见http://golang.org/pkg/encoding/json/#Marshal

a, err := json.Marshal(manegalu)

编辑:您需要将字节数组转换为字符串,以便将其与fmt.Fprint一起使用。在您的情况下,wio.Writer界面,因此您也可以使用:

w.Write(a)

打印结果而不导入fmt包。见http://golang.org/pkg/io/#Writer

答案 1 :(得分:0)

完成了。

a, err := json.Marshal(manegalu) //get json byte array
n := len(a)   //Find the length of the byte array
s := string(a[:n]) //convert to string
fmt.Fprint(w, s) //write to response