package query import ( "database/sql" "fmt" ) // RowsToMap converts a query result to a list of maps. func RowsToMap(rows *sql.Rows) ([]map[string]interface{}, error) { empty := []map[string]interface{}{} res := []map[string]interface{}{} cols, err := rows.Columns() if err != nil { return empty, fmt.Errorf("could not get columns: %v", err) } for rows.Next() { if rows.Err() != nil { return empty, fmt.Errorf("could not iterate rows: %v", err) } raw := make([]interface{}, len(cols)) for i, _ := range raw { raw[i] = new(interface{}) } if err := rows.Scan(raw...); err != nil { return empty, fmt.Errorf("could not scan row: %v", err) } row := map[string]interface{}{} for i, col := range cols { row[col] = raw[i] } res = append(res, row) } return res, nil }