-
Notifications
You must be signed in to change notification settings - Fork 0
/
c2j.go
104 lines (83 loc) · 1.75 KB
/
c2j.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"bufio"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"github.com/urfave/cli"
"github.com/andybalholm/crlf"
)
func main() {
app := cli.NewApp()
app.Name = "c2j"
app.UsageText = "./c2j input.csv [options] > output.json"
app.Description = "A simple cli tool for converting csv to json"
app.Version = "0.0.1"
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "noheaders, nh",
Usage: "specifies that the input file has no headers",
},
}
app.Action = func(c *cli.Context) error {
fileName := c.Args().First()
if fileName == "" {
return errors.New("Must specify an input file")
}
return run(fileName, c.Bool("noheaders"))
}
err := app.Run(os.Args)
if err != nil {
fmt.Printf("%v\n", err.Error())
}
}
func run(inputFile string, noHeaders bool) error {
f, err := os.Open(inputFile)
if err != nil {
return err
}
defer f.Close()
csvReader := csv.NewReader(bufio.NewReader(crlf.NewReader(f)))
csvReader.TrimLeadingSpace = true
var headers []string
if noHeaders == false {
headers, err = csvReader.Read()
if err != nil {
return err
}
}
writer := bufio.NewWriter(os.Stdout)
defer writer.Flush()
encoder := json.NewEncoder(writer)
encoder.SetEscapeHTML(false)
writer.WriteString("[\n")
first := true
for parsed, err := csvReader.Read(); err != io.EOF; parsed, err = csvReader.Read() {
if err != nil {
return err
}
if first {
first = !first
} else {
writer.WriteString(",")
}
m := make(map[string]string)
if headers != nil {
for idx, header := range headers {
if parsed[idx] == "" {
delete(m, header)
continue
}
m[header] = parsed[idx]
}
encoder.Encode(m)
} else {
encoder.Encode(parsed)
}
}
writer.WriteString("]")
return nil
}