Created
February 18, 2020 01:41
-
-
Save u110/3d3d054ba7867478ac67679d95319256 to your computer and use it in GitHub Desktop.
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" | |
"strings" | |
) | |
func main() { | |
log.Print("start") | |
csvBuf := `ID,NAME,GRADE | |
1,taro,mid | |
2,jiro,high` | |
r := csv.NewReader(strings.NewReader(csvBuf)) | |
// Header | |
record, err := r.Read() | |
if err == io.EOF { | |
log.Fatal("csv EOF") | |
} | |
if err != nil { | |
log.Fatal(err) | |
} | |
colNames := make([]string, len(record)) | |
for i, cname := range record { | |
colNames[i] = cname | |
} | |
for { | |
record, err := r.Read() | |
if err == io.EOF { | |
log.Fatal("csv EOF") | |
break | |
} | |
if err != nil { | |
log.Fatal(err) | |
} | |
jsonMap := map[string]string{} | |
for i, val := range record { | |
jsonMap[colNames[i]] = val | |
} | |
jsonBuf, err := json.Marshal(jsonMap) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("%s\n", string(jsonBuf)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment