-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv2json.go
More file actions
66 lines (56 loc) · 1.52 KB
/
csv2json.go
File metadata and controls
66 lines (56 loc) · 1.52 KB
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"
"strconv"
"strings"
)
// Header csv header metadata
type Header struct {
Name, Type string
Default interface{}
}
// Convert convert csv to json with optional headers
func Convert(data string, headers []Header) string {
reader := csv.NewReader(strings.NewReader(data))
lines, _ := reader.ReadAll()
result := []map[string]interface{}{}
for rowIndex, line := range lines {
if len(headers) == 0 && rowIndex == 0 {
headers = convertFirstLineToHeader(line)
continue
}
result = append(result, convertLineToJSONObject(line, headers))
}
jsonBytes, _ := json.Marshal(result)
return string(jsonBytes[:])
}
// ConvertStringValue convert string value to proper json type
func ConvertStringValue(stringValue string, jsonType string) (interface{}, error) {
if jsonType == "number" {
return strconv.Atoi(stringValue)
} else if jsonType == "boolean" {
return strconv.ParseBool(stringValue)
} else {
return stringValue, nil
}
}
func convertFirstLineToHeader(lineValues []string) []Header {
headers := []Header{}
for _, key := range lineValues {
headers = append(headers, Header{Name: key})
}
return headers
}
func convertLineToJSONObject(lineValues []string, headers []Header) map[string]interface{} {
jsonObj := make(map[string]interface{})
for col, header := range headers {
value, err := ConvertStringValue(lineValues[col], header.Type)
if err == nil {
jsonObj[header.Name] = value
} else {
jsonObj[header.Name] = header.Default
}
}
return jsonObj
}