Skip to content
Snippets Groups Projects
main.go 910 B
Newer Older
  • Learn to ignore specific revisions
  • Jonas Leder's avatar
    Jonas Leder committed
    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)
    	}
    }