I am trying to convert a SQL Output (GORP) to JSON. I am using gorp with mySql.
Here is my selected code
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))
}
I am expecting and output like this
{"mane_id":3323, "manetana":"ABC", "yajamana":"hgy"},{"mane_id":2323, "manetana":"ADFC", "yajamana":"FDER"},{"mane_id":12343, "manetana":"GDSC", "yajamana":"hFDEy"}
Can you please let me know what am I doing wrong? I understand that why option 1 does not work. But option 2 seems good for me as per https://gobyexample.com/json
Got it done.
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.Marshal()
returns two values, []byte
and error
. You're only assigning the first in your example. See http://golang.org/pkg/encoding/json/#Marshal.
a, err := json.Marshal(manegalu)
Edit: You'll need to convert the byte array to a string to use it with fmt.Fprint
. In your case, w
is an io.Writer
interface, so you can also use:
w.Write(a)
to print the results without importing the fmt
package. See http://golang.org/pkg/io/#Writer