Serializzare una tabella in JSON con Go è facile; farlo senza trasformare ogni intero in una stringa richiede un po' più di attenzione. Il trucco è fare lo scan su puntatori a interface{} e convertire solo le slice di byte.
Credito dell'approccio: https://stackoverflow.com/a/17885636/4124416
func getJSON(sqlString string) (string, error) {
rows, err := db.Query(sqlString)
if err != nil { return "", err }
defer rows.Close()
columns, err := rows.Columns()
if err != nil { return "", err }
count := len(columns)
tableData := make([]map[string]interface{}, 0)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
for rows.Next() {
for i := 0; i < count; i++ {
valuePtrs[i] = &values[i]
}
rows.Scan(valuePtrs...)
entry := make(map[string]interface{})
for i, col := range columns {
var v interface{}
val := values[i]
b, ok := val.([]byte)
if ok { v = string(b) } else { v = val }
entry[col] = v
}
tableData = append(tableData, entry)
}
jsonData, err := json.Marshal(tableData)
if err != nil { return "", err }
fmt.Println(string(jsonData))
return string(jsonData), nil
}Il motivo per cui funziona è che il driver MySQL restituisce le colonne di testo come []byte, mentre le colonne numeriche arrivano come i loro tipi nativi Go. Convertire solo le slice di byte preserva interi, float e booleani come veri valori JSON invece che stringhe tra virgolette.
Esempio di output
[{"ID":0,"Text":"Zero"},{"ID":1,"Text":"One"},{"ID":2,"Text":"Two"}]Costruire una map per riga è comodo e leggibile, anche se alloca parecchio. Per tabelle molto grandi, trasmettere in streaming ogni riga direttamente all'encoder evita di tenere l'intero result set in memoria.