-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
66 lines (54 loc) · 1.12 KB
/
main.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"os"
"strconv"
)
//Employee ... your employee field structure
type Employee struct {
FirstName string
LastName string
Address string
Age int
Email string
}
func main() {
csvFile, err := os.Open("./data.csv")
if err != nil {
fmt.Print(err.Error())
}
defer csvFile.Close()
reader := csv.NewReader(csvFile)
reader.FieldsPerRecord = -1
csvData, err := reader.ReadAll()
if err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
var emp Employee
var employees []Employee
for _, each := range csvData {
emp.FirstName = each[0]
emp.LastName = each[1]
emp.Address = each[2]
emp.Age, _ = strconv.Atoi(each[3])
emp.Email = each[4]
//Append the instance of the current emp model values to a slice of Employee
employees = append(employees, emp)
}
jsonData, err := json.Marshal(employees)
if err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
fmt.Print(string(jsonData))
jsonFile, err := os.Create("./data.json")
if err != nil {
fmt.Print(err.Error())
}
defer jsonFile.Close()
jsonFile.Write(jsonData)
jsonFile.Close()
}