main
Bel LaPointe 2025-02-23 16:51:26 -07:00
commit 5463c2d05a
2 changed files with 46 additions and 0 deletions

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module csv-to-json
go 1.22.1

43
main.go Normal file
View File

@ -0,0 +1,43 @@
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"log"
"os"
"strconv"
)
func main() {
parser := csv.NewReader(os.Stdin)
fields, err := parser.Read()
if err != nil {
panic(err)
}
n := 0
for {
n += 1
line, err := parser.Read()
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
if len(line) != len(fields) {
log.Println("[WARN]", "line", n, "has", len(line), "fields but only", len(fields), "are known")
}
lineResult := map[string]string{}
for i := range line {
k := strconv.Itoa(i)
if i < len(fields) {
k = fields[i]
}
lineResult[k] = line[i]
}
b, _ := json.Marshal(lineResult)
fmt.Printf("%s\n", b)
}
}