Created
March 15, 2024 08:33
-
-
Save arturo-source/688da2bf9af74207c33da58feb67c1b7 to your computer and use it in GitHub Desktop.
Convert easily a CSV into a JSON using Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/csv" | |
"encoding/json" | |
"flag" | |
"fmt" | |
"os" | |
"path/filepath" | |
"strconv" | |
"strings" | |
) | |
func string2realtype(thing string) any { | |
if real, err := strconv.Atoi(thing); err == nil { | |
return real | |
} | |
if real, err := strconv.ParseFloat(thing, 64); err == nil { | |
return real | |
} | |
if real, err := strconv.ParseBool(thing); err == nil { | |
return real | |
} | |
return thing | |
} | |
func csvname2jsonname(basename string) string { | |
nameWithoutExtension := strings.TrimSuffix(basename, filepath.Ext(basename)) | |
return nameWithoutExtension + ".json" | |
} | |
func main() { | |
var inputFilename, outputFilename string | |
flag.StringVar(&inputFilename, "i", "", "Path to the input CSV") | |
flag.StringVar(&outputFilename, "o", "", "Path to the output JSON") | |
flag.Parse() | |
if inputFilename == "" { | |
flag.Usage() | |
fmt.Println("Input csv is mandatory") | |
return | |
} | |
if outputFilename == "" { | |
outputFilename = csvname2jsonname(inputFilename) | |
} | |
csvfile, err := os.Open(inputFilename) | |
if err != nil { | |
fmt.Println("Error opening CSV file:", err) | |
return | |
} | |
defer csvfile.Close() | |
reader := csv.NewReader(csvfile) | |
records, err := reader.ReadAll() | |
if err != nil { | |
fmt.Println("Error reading CSV records:", err) | |
return | |
} | |
var jsonData []map[string]any | |
for _, record := range records[1:] { | |
entry := make(map[string]any) | |
for i, value := range record { | |
entry[records[0][i]] = string2realtype(value) | |
} | |
jsonData = append(jsonData, entry) | |
} | |
jsonfile, err := os.Create(outputFilename) | |
if err != nil { | |
fmt.Println("Error creating file:", err) | |
return | |
} | |
err = json.NewEncoder(jsonfile).Encode(jsonData) | |
if err != nil { | |
fmt.Println("Error encoding JSON:", err) | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment