|
| 1 | +// |
| 2 | +// csv2json - is a command line that takes CSV input from stdin and |
| 3 | +// writes out JSON expression. It includes support for using the first |
| 4 | +// row as field names or default fieldnames (e.g. col0, col1, col2). |
| 5 | +// Additionally it can output the resulting JSON data structures as a |
| 6 | +// JSON array or individual JSON blobs (one line per blob). |
| 7 | +// |
| 8 | +// @author R. S. Doiel, <[email protected]> |
| 9 | +// |
| 10 | +// Copyright (c) 2017, Caltech |
| 11 | +// All rights not granted herein are expressly reserved by Caltech. |
| 12 | +// |
| 13 | +// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: |
| 14 | +// |
| 15 | +// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. |
| 16 | +// |
| 17 | +// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. |
| 18 | +// |
| 19 | +// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. |
| 20 | +// |
| 21 | +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 22 | +// |
| 23 | +package main |
| 24 | + |
| 25 | +import ( |
| 26 | + "encoding/csv" |
| 27 | + "encoding/json" |
| 28 | + "flag" |
| 29 | + "fmt" |
| 30 | + "io" |
| 31 | + "os" |
| 32 | + "path" |
| 33 | + "strings" |
| 34 | + |
| 35 | + // My packages |
| 36 | + "github.com/caltechlibrary/cli" |
| 37 | + "github.com/caltechlibrary/datatools" |
| 38 | +) |
| 39 | + |
| 40 | +var ( |
| 41 | + usage = `USAGE: %s [OPTIONS]` |
| 42 | + |
| 43 | + description = ` |
| 44 | +SYNOPSIS |
| 45 | +
|
| 46 | +%s reads CSV from stdin and writes a JSON to stdout. JSON output |
| 47 | +can be either an array of JSON blobs or one JSON blob (row as object) |
| 48 | +per line. |
| 49 | +` |
| 50 | + |
| 51 | + examples = ` |
| 52 | +EXAMPLES |
| 53 | +
|
| 54 | +Convert data1.csv to data1.json using Unix pipes. |
| 55 | +
|
| 56 | + cat data1.csv | %s > data1.json |
| 57 | +
|
| 58 | +Convert data1.csv to JSON blobs, one line per blob |
| 59 | +
|
| 60 | + %s -as-blobs -i data1.csv |
| 61 | +` |
| 62 | + |
| 63 | + // Standard Options |
| 64 | + showHelp bool |
| 65 | + showLicense bool |
| 66 | + showVersion bool |
| 67 | + inputFName string |
| 68 | + outputFName string |
| 69 | + |
| 70 | + // Application Options |
| 71 | + useHeader bool |
| 72 | + asBlobs bool |
| 73 | +) |
| 74 | + |
| 75 | +func init() { |
| 76 | + // Standard Options |
| 77 | + flag.BoolVar(&showHelp, "h", false, "display help") |
| 78 | + flag.BoolVar(&showHelp, "help", false, "display help") |
| 79 | + flag.BoolVar(&showLicense, "l", false, "display license") |
| 80 | + flag.BoolVar(&showLicense, "license", false, "display license") |
| 81 | + flag.BoolVar(&showVersion, "v", false, "display version") |
| 82 | + flag.BoolVar(&showVersion, "version", false, "display version") |
| 83 | + flag.StringVar(&inputFName, "i", "", "input filename") |
| 84 | + flag.StringVar(&inputFName, "input", "", "input filename") |
| 85 | + flag.StringVar(&outputFName, "o", "", "output filename") |
| 86 | + flag.StringVar(&outputFName, "output", "", "output filename") |
| 87 | + |
| 88 | + // App Options |
| 89 | + flag.BoolVar(&useHeader, "use-header", true, "treat the first row as field names") |
| 90 | + flag.BoolVar(&asBlobs, "as-blobs", false, "output as one JSON blob per line") |
| 91 | +} |
| 92 | + |
| 93 | +func main() { |
| 94 | + appName := path.Base(os.Args[0]) |
| 95 | + flag.Parse() |
| 96 | + |
| 97 | + // Configuration and command line interation |
| 98 | + cfg := cli.New(appName, appName, fmt.Sprintf(datatools.LicenseText, appName, datatools.Version), datatools.Version) |
| 99 | + cfg.UsageText = fmt.Sprintf(usage, appName) |
| 100 | + cfg.DescriptionText = fmt.Sprintf(description, appName) |
| 101 | + cfg.ExampleText = fmt.Sprintf(examples, appName, appName) |
| 102 | + |
| 103 | + if showHelp == true { |
| 104 | + fmt.Println(cfg.Usage()) |
| 105 | + os.Exit(0) |
| 106 | + } |
| 107 | + |
| 108 | + if showLicense == true { |
| 109 | + fmt.Println(cfg.License()) |
| 110 | + os.Exit(0) |
| 111 | + } |
| 112 | + |
| 113 | + if showVersion == true { |
| 114 | + fmt.Println(cfg.Version()) |
| 115 | + os.Exit(0) |
| 116 | + } |
| 117 | + |
| 118 | + in, err := cli.Open(inputFName, os.Stdin) |
| 119 | + if err != nil { |
| 120 | + fmt.Fprintf(os.Stderr, "%s\n", err) |
| 121 | + os.Exit(1) |
| 122 | + } |
| 123 | + defer cli.CloseFile(inputFName, in) |
| 124 | + |
| 125 | + out, err := cli.Create(outputFName, os.Stdout) |
| 126 | + if err != nil { |
| 127 | + fmt.Fprintf(os.Stderr, "%s\n", err) |
| 128 | + os.Exit(1) |
| 129 | + } |
| 130 | + defer cli.CloseFile(outputFName, out) |
| 131 | + |
| 132 | + rowNo := 0 |
| 133 | + fieldNames := []string{} |
| 134 | + r := csv.NewReader(in) |
| 135 | + if useHeader == true { |
| 136 | + row, err := r.Read() |
| 137 | + if err == io.EOF { |
| 138 | + fmt.Fprintf(os.Stderr, "No data\n") |
| 139 | + os.Exit(1) |
| 140 | + } |
| 141 | + if err != nil { |
| 142 | + fmt.Fprintf(os.Stderr, "%s\n", err) |
| 143 | + os.Exit(1) |
| 144 | + } |
| 145 | + for _, val := range row { |
| 146 | + fieldNames = append(fieldNames, strings.TrimSpace(val)) |
| 147 | + } |
| 148 | + rowNo++ |
| 149 | + } |
| 150 | + arrayOfObjects := []string{} |
| 151 | + object := map[string]interface{}{} |
| 152 | + for { |
| 153 | + row, err := r.Read() |
| 154 | + if err == io.EOF { |
| 155 | + break |
| 156 | + } |
| 157 | + if err != nil { |
| 158 | + fmt.Fprintf(os.Stderr, "%s\n", err) |
| 159 | + os.Exit(1) |
| 160 | + } |
| 161 | + // Pad the fieldnames if necessary |
| 162 | + object = map[string]interface{}{} |
| 163 | + for col, val := range row { |
| 164 | + if col < len(fieldNames) { |
| 165 | + object[fieldNames[col]] = val |
| 166 | + } else { |
| 167 | + object[fmt.Sprintf("col_%d", col)] = val |
| 168 | + } |
| 169 | + } |
| 170 | + src, err := json.Marshal(object) |
| 171 | + if err != nil { |
| 172 | + fmt.Fprintf(os.Stderr, "error row %d, %s\n", rowNo, err) |
| 173 | + } |
| 174 | + if asBlobs == true { |
| 175 | + fmt.Fprintf(os.Stdout, "%s\n", src) |
| 176 | + } else { |
| 177 | + arrayOfObjects = append(arrayOfObjects, string(src)) |
| 178 | + } |
| 179 | + rowNo++ |
| 180 | + } |
| 181 | + if asBlobs == false { |
| 182 | + fmt.Fprintf(os.Stdout, "[%s]\n", strings.Join(arrayOfObjects, ",")) |
| 183 | + } |
| 184 | +} |
0 commit comments