Converting CSV data to JSON with Go
CSV is one of the most frequently used data formats in the last period of software technologies. Particularly, with the development of technologies with BigData and data-oriented architects, data exchange, import and export operations with CSV have become even more valuable. In this example, we will examine how to convert a CSV export to the JSON data format using the Go programming language. Both of these formats are very often used.
A sample CSV data (data.csv);
Cihan,Özhan,29 Kerim,Fırat,36 Emre,Okumuş,35 Barış,Özhan,30
Go code of the program;
package main import ( "encoding/csv" "encoding/json" "fmt" "os" "strconv" ) type Employee struct { FirstName string LastName string Age int } func main() { csvFile, err := os.Open("./data.csv") if err != nil { fmt.Println(err) } defer csvFile.Close() reader := csv.NewReader(csvFile) reader.FieldsPerRecord = -1 csvData, err := reader.ReadAll() if err != nil { fmt.Println(err) os.Exit(1) } var emp Employee var employees []Employee for _, each := range csvData { emp.FirstName = each[0] emp.LastName = each[1] emp.Age, _ = strconv.Atoi(each[2]) employees = append(employees, emp) } // Convert to JSON jsonData, err := json.Marshal(employees) if err != nil { fmt.Println(err) os.Exit(1) } fmt.Println(string(jsonData)) jsonFile, err := os.Create("./data.json") if err != nil { fmt.Println(err) } defer jsonFile.Close() jsonFile.Write(jsonData) jsonFile.Close() }
When you run the application, it will generate a JSON file with the name data.json as output.
The content of this file is as follows;
[ {"FirstName":"Cihan","LastName":"Özhan","Age":29}, {"FirstName":"Kerim","LastName":"Fırat","Age":36}, {"FirstName":"Emre","LastName":"Okumuş","Age":35}, {"FirstName":"Barış","LastName":"Özhan","Age":30} ]
Good work!
Cihan Özhan