Debian Codegraph @

csv-to-json.go

raw symbols SCIP
1 package csv
2
3 import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "regexp"
8 "strings"
9 )
10
11 // Given a stream of CSV records, generate a stream of JSON records, one per line. The headers
12 // are treated as paths into the resulting JSON object, so a CSV file containing the header
13 // foo.bar,baz and the data 1, 2 will be converted into a JSON object like {"foo": {"bar": 1}, "baz": 2}
14 //
15 // If column values can be successfully unmarshalled as JSON numbers, booleans, objects or arrays then
16 // the value will be encoded as the corresponding JSON object, otherwise it will be encoded as a string.
17 // Use --strings to force all column values to be encoded as JSON strings.
18 //
19 type CsvToJsonProcess struct {
20 BaseObject string
21 StringsOnly bool
22 }
23
24 func (proc *CsvToJsonProcess) writeToMap(m map[string]interface{}, p []string, v interface{}) {
25 if len(p) == 1 {
26 m[p[0]] = v
27 } else if len(p) > 1 {
28 var o interface{}
29 var mo map[string]interface{}
30 var ok bool
31 if o, ok = m[p[0]]; !ok {
32 mo = map[string]interface{}{}
33 } else {
34 if mo, ok = o.(map[string]interface{}); !ok {
35 mo = map[string]interface{}{}
36 }
37 }
38 m[p[0]] = mo
39 proc.writeToMap(mo, p[1:], v)
40 }
41
42 }
43
44 func (p *CsvToJsonProcess) Run(reader Reader, encoder *json.Encoder, errCh chan<- error) {
45 errCh <- func() (err error) {
46 defer reader.Close()
47
48 baseObject := p.BaseObject
49 stringsOnly := p.StringsOnly
50
51 // open the reader
52 paths := map[string][]string{}
53 for _, k := range reader.Header() {
54 paths[k] = strings.Split(k, ".")
55 }
56
57 if baseObject != "" {
58 if _, ok := paths[baseObject]; !ok {
59 return fmt.Errorf("fatal: '%s' is not a valid key in the input stream", baseObject)
60 }
61 }
62
63 // see: http://stackoverflow.com/questions/13340717/json-numbers-regular-expression
64 numberMatcher := regexp.MustCompile("^ *-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)? *$")
65
66 for data := range reader.C() {
67 dataMap := data.AsMap()
68 objectMap := map[string]interface{}{}
69
70 if baseObject != "" {
71 if base, ok := dataMap[baseObject]; ok {
72 if err := json.Unmarshal([]byte(base), &objectMap); err != nil {
73 fmt.Fprintf(os.Stderr, "warning: failed to parse base object: %s: %s\n", base, err)
74 }
75 }
76 }
77
78 for k, v := range dataMap {
79 var f float64
80 var ov interface{}
81
82 ov = v
83
84 if baseObject != "" && k == baseObject {
85 continue
86 } else if v == "" {
87 continue
88 } else if stringsOnly {
89 ov = v
90 } else if v == "null" {
91 continue
92 } else if v == "true" || v == "TRUE" {
93 ov = true
94 } else if v == "false" || v == "FALSE" {
95 ov = false
96 } else if v[0] == '{' {
97 j := map[string]interface{}{}
98 if err := json.Unmarshal([]byte(v), &j); err == nil {
99 ov = j
100 }
101 } else if v[0] == '[' {
102 aj := make([]interface{}, 0)
103 if err := json.Unmarshal([]byte(v), &aj); err == nil {
104 ov = aj
105 }
106 } else if numberMatcher.MatchString(v) {
107 if _, err := fmt.Sscanf(v, "%f", &f); err == nil {
108 ov = f
109 }
110 }
111 p.writeToMap(objectMap, paths[k], ov)
112 }
113 encoder.Encode(objectMap)
114 }
115 return reader.Error()
116 }()
117 }