Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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)
}
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 {
header := make([]string, 0, len(data))
for key := range data {
header = append(header, key)
}
if err := writer.Write(header); err != nil {
panic(err)
}
}
row := make([]string, 0, len(data))
for _, value := range data {
row = append(row, helper.AnyToString(value))
}
if err := writer.Write(row); err != nil {
panic(err)
}
}