gpt4 book ai didi

json - Gorm 输出到 json

转载 作者:IT王子 更新时间:2023-10-29 02:05:41 26 4
gpt4 key购买 nike

我正在尝试将 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 对我来说似乎不错

最佳答案

搞定了。

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

关于json - Gorm 输出到 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27133761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com