As a complete newbie I think of marshal a complete list instead of each row
for rows.Next() {
err = rows.Scan(vals...)
append (list, vals) //save to a list
}
json, _ := json.Marshal(list) //marshal the list instead of each row
fmt.Fprintf(w,"%s\n",json)
var arr []string
for rows.Next() {
err = rows.Scan(vals…)
m := make(map[string]interface{})
for i, v := range vals {
m[colnames[i]] = v
}
str, _ := json.Marshal(m)
arr = append(arr, string(str))
}
You’re doing tricky stuff with pointers to a slice of values, and always scanning into the same slice (vals, containing pointers to cols), overriding the values. I appreciate that you’re trying to do something completely dynamic based on the table structure but the level of indirection in the initial code makes even me frown a bit.
You are dealing with a complete newbie on Golang. Learning by doing.
The main goal is to fetch data from SQL without knowing the struct AND parse this into JSON. I am beginning to think that this is either impossible or too hard for a newbie.
Hi, I did no test code so I got curious about why it return the same data always.
In the code below, I think a map is create in every call
var arr []map[string]interface{}
for rows.Next() {
err = rows.Scan(vals…)
m := make(map[string]interface{})
for i, v := range vals {
m[colnames[i]] = v
}
str, _ := json.Marshal(m)
fmt.Println(string(str))
arr = append(arr, m)
}
json, _ := json.Marshal(arr)
fmt.Println(string(json))
In fact, the data in the map is correctly shown and then the map (new pointer) is added to the slice so it is no possible to rewrite it. However,when write the slice, only shows the last one