You may be missing a "continue" in your "if cont == 0" block.
Seth On Nov 28, 2016 7:33 AM, "Sergio Hunter" <ohot...@gmail.com> wrote: > Hi everybody. I need help. When outputting data to a csv file, the dates > is duplicated, but should merge and be counted. How to write correctly? > Thanks. > > > > package main > > import ( > "database/sql" > "log" > _"github.com/go-sql-driver/mysql" > "compress/zlib" > "bytes" > "encoding/json" > "io/ioutil" > "sort" > "encoding/csv" > "os" > "strconv" > "fmt" > ) > > var ( > data []byte > dates []string > ) > > type UserStatsData struct { > Dates map[string]Info `json:"d"` > } > > type Info struct { > D string `json:"-"` > G int `json:"g"` > R json.Number `json:"r"` > } > > func main() > > db, err := sql.Open("mysql", > "name:password@tcp(127.0.0.1:port)/database") > if err != nil { > panic(err.Error()) > } > defer db.Close() > > rows, err := db.Query(`SELECT data FROM user_stats ORDER BY created_at > LIMIT 5`) > if err != nil { > log.Fatal(err) > } > defer rows.Close() > > file, err := os.Create("result.csv") > if err != nil { > fmt.Println(err) > } > defer file.Close() > > cont := 0 > writer := csv.NewWriter(file) > userStatsData := UserStatsData{} > for rows.Next() { > err := rows.Scan(&data) > if err != nil { > log.Fatal(err) > } > > if err := json.Unmarshal(data, &userStatsData); err != nil { > r, err := zlib.NewReader(bytes.NewReader(data)) > if err != nil { > log.Panicf("\nCannot read archive %v", err) > } > r.Close() > data, _ = ioutil.ReadAll(r) > } > //fmt.Printf("%s\n", data) > if err := json.Unmarshal(data, &userStatsData); err != nil{ > panic(err) > } > > for userStats := range userStatsData.Dates { > dates = append(dates, userStats) > } > sort.Strings(dates) > > var info []Info > for _, date := range dates { > k := userStatsData.Dates[date] > k.D = date > info = append(info, k) > } > > for _, i := range info { > if cont == 0 { > var record []string > record = append(record, "Date") > record = append(record, "Gold") > record = append(record, "Revenue") > writer.Write(record) > cont++ > > } > var record []string > record = append(record, i.D) > record = append(record, strconv.Itoa(i.G)) > record = append(record, i.R.String()) > writer.Write(record) > cont++ > > } > > writer.Flush() > err = writer.Error() > if err != nil { > panic(err) > } > > } > > } > > > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.