Last active
August 29, 2015 14:17
-
-
Save shogo82148/8f19cb771dc6f91308a7 to your computer and use it in GitHub Desktop.
csv to yaml converter
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" | |
"io" | |
"os" | |
"sort" | |
"gopkg.in/yaml.v2" | |
) | |
type sortByKey yaml.MapSlice | |
func (p sortByKey) Len() int { | |
return len(p) | |
} | |
func (p sortByKey) Less(i, j int) bool { | |
keyA := p[i].Key.(string) | |
keyB := p[j].Key.(string) | |
if keyA == keyB { | |
return false | |
} | |
if keyA == "id" { | |
return true | |
} | |
if keyB == "id" { | |
return false | |
} | |
return keyA < keyB | |
} | |
func (p sortByKey) Swap(i, j int) { | |
p[i], p[j] = p[j], p[i] | |
} | |
func main() { | |
var input io.Reader | |
var err error | |
if len(os.Args) >= 2 { | |
input, err = os.Open(os.Args[1]) | |
if err != nil { | |
panic(err) | |
} | |
} else { | |
input = os.Stdin | |
} | |
reader := csv.NewReader(input) | |
header, err := reader.Read() | |
if err != nil { | |
panic(err) | |
} | |
data := []yaml.MapSlice{} | |
for { | |
row, err := reader.Read() | |
if err == io.EOF { | |
break | |
} else if err != nil { | |
panic(err) | |
} | |
rowdata := make(yaml.MapSlice, 0, len(header)) | |
for i, name := range header { | |
if i < len(row) { | |
rowdata = append(rowdata, yaml.MapItem{ | |
Key: name, | |
Value: row[i], | |
}) | |
} | |
} | |
sort.Stable(sortByKey(rowdata)) | |
data = append(data, rowdata) | |
} | |
out, err := yaml.Marshal(data) | |
if err != nil { | |
panic(err) | |
} | |
_, err = os.Stdout.Write(out) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment