Skip to content

Instantly share code, notes, and snippets.

@MrBri
Created August 17, 2017 07:09
Show Gist options
  • Save MrBri/893ece37a3dd26dbb5411db7eacf1dd7 to your computer and use it in GitHub Desktop.
Save MrBri/893ece37a3dd26dbb5411db7eacf1dd7 to your computer and use it in GitHub Desktop.
golang csv2json
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"os"
"strconv"
)
type Pole struct {
Lat float64
Long float64
ID int
}
func main() {
// read data from CSV file
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 oneRecord Pole
var allRecords []Pole
for _, each := range csvData {
oneRecord.Lat, _ = strconv.ParseFloat(each[0], 64)
// oneRecord.Age, _ = strconv.Atoi(each[1]) // need to cast integer to string
oneRecord.Long, _ = strconv.ParseFloat(each[1], 64)
oneRecord.ID, _ = strconv.Atoi(each[1])
allRecords = append(allRecords, oneRecord)
}
jsondata, err := json.Marshal(allRecords) // convert to JSON
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// sanity check
// NOTE : You can stream the JSON data to http service as well instead of saving to file
// fmt.Println(string(jsondata))
// now write to JSON file
jsonFile, err := os.Create("./data.json")
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
jsonFile.Write(jsondata)
jsonFile.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment