I’ve a CSV File having data in below format.
Date,RestaurantId,ItemRatings
2023-10-08,232,[{"item_id":8215117,"item_name":"The Farmers Breakfast","current_day_count":0,"current_day_sum":0,"mtd_count":1,"mtd_sum":5,"wtd_count":0,"wtd_sum":0},{"item_id":8215132,"item_name":"The Great White","current_day_count":0,"current_day_sum":0,"mtd_count":1,"mtd_sum":5,"wtd_count":0,"wtd_sum":0}]
I want to parse the CSV file to store the data in a struct
type ItemRatings struct {
RestaurantId int `json:“item_id”`
Date string `json:"date"`
ItemData []ItemData `json:“item_data”`
}
type ItemData struct {
ItemID int `json:“item_id”`
ItemName string `json:“item_name”`
CurrentDayCount int `json:“current_day_count”`
CurrentDaySum int `json:“current_day_sum”`
MTDCount int `json:“mtd_count”`
MTDSum int `json:“mtd_sum”`
WTDCount int `json:“wtd_count”`
WTDSum int `json:“wtd_sum”`
}
POC code:
reader := csv.NewReader(file)
reader.LazyQuotes = true
for {
record, err := reader.Read()
if err != nil {
t.Fatalf("%v", err)
}
itemDetailsJson := record[2]
var itemDetails []ItemData
err = json.Unmarshal([]byte(itemDetailsJson), &itemDetails)
if err != nil {
t.Fatalf("Error unmarshalling: %v", err)
}
fmt.Printf("Unmarshalled Array: %+vn", itemDetails)
}
Please suggest a way to do it in Golang. Facing issues due to double quotes and commas used in the json data list. Please suggest code changes or alternative CSV format which can be used to achieve the objective with data aggregated on restaurantId field in the CSV.
3
Answers
Is that what you want ?
data.csv
script.go
You can use the encoding/csv and enconding/json packages in Go to parse the CSV data and unmarshal it into your struct. you’ll need parse the JSON data from the CSV and then unmarshal it into your ItemData struct.
Because of the encoding/csv, csv file was updated with a double quote.
I spent some time, so I added it here as an alternative way.
CSV (test.csv):
Code:
Output: