File: jsons.go 1 /* 2 The MIT License (MIT) 3 4 Copyright © 2020-2025 pacman64 5 6 Permission is hereby granted, free of charge, to any person obtaining a copy of 7 this software and associated documentation files (the “Software”), to deal 8 in the Software without restriction, including without limitation the rights to 9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 10 of the Software, and to permit persons to whom the Software is furnished to do 11 so, subject to the following conditions: 12 13 The above copyright notice and this permission notice shall be included in all 14 copies or substantial portions of the Software. 15 16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 SOFTWARE. 23 */ 24 25 /* 26 Single-file source-code for jsons. 27 28 To compile a smaller-sized command-line app, you can use the `go` command as 29 follows: 30 31 go build -ldflags "-s -w" -trimpath jsons.go 32 */ 33 34 package main 35 36 import ( 37 "bufio" 38 "io" 39 "os" 40 "strings" 41 ) 42 43 const info = ` 44 jsons [options...] [filenames...] 45 46 JSON Strings turns TSV (tab-separated values) data into a JSON array of 47 objects whose values are strings or nulls, the latter being used for 48 missing trailing values. 49 ` 50 51 // noMoreOutput is a custom error-type meant to be deliberately ignored 52 type noMoreOutput struct{} 53 54 func (nmo noMoreOutput) Error() string { 55 return `no more output` 56 } 57 58 func main() { 59 if len(os.Args) > 1 { 60 switch os.Args[1] { 61 case `-h`, `--h`, `-help`, `--help`: 62 os.Stdout.WriteString(info[1:]) 63 return 64 } 65 } 66 67 err := run(os.Args[1:]) 68 if _, ok := err.(noMoreOutput); ok { 69 err = nil 70 } 71 72 if err != nil { 73 os.Stderr.WriteString("\x1b[31m") 74 os.Stderr.WriteString(err.Error()) 75 os.Stderr.WriteString("\x1b[0m\n") 76 os.Exit(1) 77 } 78 } 79 80 type runConfig struct { 81 lines int 82 keys []string 83 } 84 85 func run(paths []string) error { 86 bw := bufio.NewWriter(os.Stdout) 87 defer bw.Flush() 88 89 dashes := 0 90 var cfg runConfig 91 92 for _, path := range paths { 93 if path == `-` { 94 dashes++ 95 if dashes > 1 { 96 continue 97 } 98 99 if err := handleInput(bw, os.Stdin, &cfg); err != nil { 100 return err 101 } 102 103 continue 104 } 105 106 if err := handleFile(bw, path, &cfg); err != nil { 107 return err 108 } 109 } 110 111 if len(paths) == 0 { 112 if err := handleInput(bw, os.Stdin, &cfg); err != nil { 113 return err 114 } 115 } 116 117 if cfg.lines > 1 { 118 bw.WriteString("\n]\n") 119 } else { 120 bw.WriteString("[]\n") 121 } 122 return nil 123 } 124 125 func handleFile(w *bufio.Writer, path string, cfg *runConfig) error { 126 f, err := os.Open(path) 127 if err != nil { 128 return err 129 } 130 defer f.Close() 131 return handleInput(w, f, cfg) 132 } 133 134 func escapeKeys(line string) []string { 135 var keys []string 136 var sb strings.Builder 137 138 loopTSV(line, func(i int, s string) { 139 sb.WriteByte('"') 140 for _, r := range s { 141 if r == '\\' || r == '"' { 142 sb.WriteByte('\\') 143 } 144 sb.WriteRune(r) 145 } 146 sb.WriteByte('"') 147 148 keys = append(keys, sb.String()) 149 sb.Reset() 150 }) 151 152 return keys 153 } 154 155 func emitRow(w *bufio.Writer, line string, keys []string) { 156 j := 0 157 w.WriteByte('{') 158 159 loopTSV(line, func(i int, s string) { 160 j = i 161 if i > 0 { 162 w.WriteString(", ") 163 } 164 165 w.WriteString(keys[i]) 166 w.WriteString(": \"") 167 168 for _, r := range s { 169 if r == '\\' || r == '"' { 170 w.WriteByte('\\') 171 } 172 w.WriteRune(r) 173 } 174 w.WriteByte('"') 175 }) 176 177 for i := j + 1; i < len(keys); i++ { 178 if i > 0 { 179 w.WriteString(", ") 180 } 181 w.WriteString(keys[i]) 182 w.WriteString(": null") 183 } 184 w.WriteByte('}') 185 } 186 187 func loopTSV(line string, f func(i int, s string)) { 188 for i := 0; len(line) > 0; i++ { 189 pos := strings.IndexByte(line, '\t') 190 if pos < 0 { 191 f(i, line) 192 return 193 } 194 195 f(i, line[:pos]) 196 line = line[pos+1:] 197 } 198 } 199 200 func handleInput(w *bufio.Writer, r io.Reader, cfg *runConfig) error { 201 const gb = 1024 * 1024 * 1024 202 sc := bufio.NewScanner(r) 203 sc.Buffer(nil, 8*gb) 204 205 for sc.Scan() { 206 if cfg.lines == 0 { 207 cfg.keys = escapeKeys(sc.Text()) 208 w.WriteByte('[') 209 cfg.lines++ 210 continue 211 } 212 213 if cfg.lines == 1 { 214 w.WriteString("\n ") 215 } else { 216 if _, err := w.WriteString(",\n "); err != nil { 217 return noMoreOutput{} 218 } 219 } 220 221 emitRow(w, sc.Text(), cfg.keys) 222 cfg.lines++ 223 } 224 225 return sc.Err() 226 }