Last active
March 10, 2020 13:13
-
-
Save jvgutierrez/5e7b431463c873c7342562e04a5e39a6 to your computer and use it in GitHub Desktop.
tsv2json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/csv" | |
"encoding/json" | |
"fmt" | |
"io" | |
"log" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
in := "a:b\tc:1\td:blablebli" | |
numericFields := map[string]bool{ | |
"c": true, | |
} | |
r := csv.NewReader(strings.NewReader(in)) | |
r.Comma = '\t' | |
for { | |
fields, err := r.Read() | |
if err == io.EOF { | |
break | |
} | |
if err != nil { | |
log.Fatal(err) | |
} | |
type jsonData map[string]interface{} | |
data := jsonData{} | |
for _, field := range fields { | |
values := strings.SplitN(field, ":", 2) | |
key := values[0] | |
value := values[1] | |
if numericFields[key] { | |
intValue, err := strconv.Atoi(value) | |
if err == nil { | |
data[key] = intValue | |
} else { | |
data[key] = value | |
} | |
} else { | |
data[key] = value | |
} | |
} | |
j, err := json.Marshal(data) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(string(j)) | |
} | |
} | |
// output: {"a":"b","c":1,"d":"blablebli"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment