jszwec/csvutil 高性能、惯用的CSV记录编码和解码到本机Go结构
文档
安装
bash
go get github.com/jszwec/csvutil
要读取的文件 user.csv
name,age,CreatedAt
jacek,26,2012-04-01T15:00:00Z
john,,2001-01-01T00:00:00Z
读取示例
go
package main
import (
"encoding/json"
"fmt"
"os"
"time"
"github.com/jszwec/csvutil"
)
type User struct {
Name string `csv:"name"`
Age int `csv:"age,omitempty"`
CreatedAt time.Time
}
func main() {
body, _ := os.ReadFile("./user.csv")
var users []User
// read csv
csvutil.Unmarshal(body, &users)
// out
data, _ := json.MarshalIndent(users, "", " ")
fmt.Println(string(data))
}
转为json输出
json
[
{
"Name": "jacek",
"Age": 26,
"CreatedAt": "2012-04-01T15:00:00Z"
},
{
"Name": "john",
"Age": 0,
"CreatedAt": "2001-01-01T00:00:00Z"
}
]