Newer
Older
package csv
import (
"encoding/csv"
"encoding/json"
"os"
"jonasled.dev/jonasled/ems-esp-logger/helper"
)
func JsonToCsv(jsonData string) {
var data map[string]interface{}
if err := json.Unmarshal([]byte(jsonData), &data); err != nil {
panic(err)
}
currentDate := time.Now().Format("2006-01-02 13:44")
file, err := os.OpenFile(os.Getenv("OUTPUT_FILE_NAME"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
fileInfo, err := file.Stat()
if err != nil {
panic(err)
}
if fileInfo.Size() == 0 {
// Write header
header := []string{"Date"}
for key := range data {
header = append(header, key)
}
if err := writer.Write(header); err != nil {
panic(err)
}
}
// Write data as a single line with the date
row := []string{currentDate}
for _, value := range data {
row = append(row, helper.AnyToString(value))
}
if err := writer.Write(row); err != nil {
panic(err)
}
}