If I have a csv read into a struct how can I manipulate the input to build the struct how I want? I am getting stuck in circles following various tutorials. This is the closest I have come.
I essentially want to open a csv, read selected columns, ensure the value is recorded from the same row when referencing the column. Then the resulting data in a format which can be put into a database.
Example CSV:
Ignore,Customer,Fruit,Number
123,A,Apple,1
123,A,Apple,3
123,B,Orange,4
123,C,Melon,5
Example Code:
package main
import (
"bufio"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"log"
"os"
)
type Account struct {
Customer string `json:"Customer"`
LineItem *LineItem `json:"LineItem"`
}
type LineItem struct {
ProductName string `json:"ProductName"`
Count string `json:"Count"`
}
func main() {
csvFile, _ := os.Open("/home/frank/gocode/src/local/billing/fruit.csv")
reader := csv.NewReader(bufio.NewReader(csvFile))
var billData []Account
for {
line, error := reader.Read()
if error == io.EOF {
break
} else if error != nil {
log.Fatal(error)
}
billData = append(billData, Account{
Customer: line[1],
LineItem: &LineItem{
ProductName: line[2],
Count: line[3],
},
})
}
billingJson, _ := json.Marshal(billData)
fmt.Println(string(billingJson))
}
The current output is:
[{"Customer":"Customer","LineItem":{"ProductName":"Fruit","Count":"Number"}},{"Customer":"A","LineItem":{"ProductName":"Apple","Count":"1"}},{"Customer":"A","LineItem":{"ProductName":"Apple","Count":"3"}},{"Customer":"B","LineItem":{"ProductName":"Orange","Count":"4"}},{"Customer":"C","LineItem":{"ProductName":"Melon","Count":"5"}}]
I would like to get rid of first record so the headers are not kept. e.g.
[{"Customer":"A","LineItem":{"ProductName":"Apple","Count":"1"}},{"Customer":"A","LineItem":{"ProductName":"Apple","Count":"3"}},{"Customer":"B","LineItem":{"ProductName":"Orange","Count":"4"}},{"Customer":"C","LineItem":{"ProductName":"Melon","Count":"5"}}]
Consolidate so Customer A is one record with both LineItems e.g.
[{"Customer":"A","LineItem":{"ProductName":"Apple","Count":"1"},"LineItem":{"ProductName":"Apple","Count":"3"}},{"Customer":"B","LineItem":{"ProductName":"Orange","Count":"4"}},{"Customer":"C","LineItem":{"ProductName":"Melon","Count":"5"}}]
Any best practices - alternate methods welcomed (not sure if a map is better here). Hopefully enough info to give me a hand.