-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcsv_json_parser.go
54 lines (48 loc) · 1.04 KB
/
csv_json_parser.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
package main
import (
"encoding/csv"
"fmt"
"io"
"strings"
"bytes"
)
// parses the raw stats CSV output to a json string
func parse_csv(csvInput string) (string, error){
csvReader := csv.NewReader(strings.NewReader(csvInput))
lineCount := 0
var headers []string
var result bytes.Buffer
var item bytes.Buffer
result.WriteString("[")
for {
// read just one record, but we could ReadAll() as well
record, err := csvReader.Read()
if err == io.EOF {
result.Truncate(int(len(result.String())-1))
result.WriteString("]")
break
} else if err != nil {
fmt.Println("Error:", err)
return "", err
}
if lineCount == 0 {
headers = record[:]
lineCount += 1
} else
{
item.WriteString("{")
for i := 0; i < len(headers); i++ {
item.WriteString("\"" + headers[i] + "\": \"" + record[i] + "\"")
if i == (len(headers)-1) {
item.WriteString("}")
} else {
item.WriteString(",")
}
}
result.WriteString(item.String() + ",")
item.Reset()
lineCount += 1
}
}
return result.String(), nil
}