Converting CSV data to JSON with Go

Cihan Ozhan
1 min readNov 8, 2021

Converting CSV data to JSON with Go

I wrote this code in 2016 but re-shared it for newbies.

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,89
Murtaza,Can,75
Abuzittin,Kıprak,45
Sude,Su,99

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":89},
{"FirstName":"Murtaza","LastName":"Can","Age":75},
{"FirstName":"Abuzittin","Kıprak":"Okumuş","Age":45},
{"FirstName":"Sude","LastName":"Su","Age":99}
]

Good luck
Cihan Özhan

--

--