Golang解析CSV文件
日常工作實用CSV類型文件很普遍,而且很容易從其他數據源中獲得。如Google Sheets,Microsoft Excel,或關係型數據庫。如何在應用中加載並解析CSV呢,本文帶你實用Golang解析csv文件。
1. 概述
通常其他語言處理CSV文件比較麻煩,通常需要通過第三方庫,解析工作量較大。Golang中內置了encoding/csv
包,讓解析工作變得很簡單。
假設我們的數據結構爲:姓名、年齡、省份、城市
張勇,24,江蘇,南京
李婉,23,山東,濟南
張飛,33,,
上面數據表示一組人信息。包括多行、列,我們的任務是加載數據並生成json類型數據。
2. 代碼實現
package main
import (
"bufio"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"log"
"os"
"strconv"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Address *Address `json:"address,omitempty"`
}
type Address struct {
State string `json:"state"`
City string `json:"city"`
}
func main() {
csvFile, _ := os.Open("person.csv")
reader := csv.NewReader(bufio.NewReader(csvFile))
var people []Person
for {
line, error := reader.Read()
if error == io.EOF {
break
} else if error != nil {
log.Fatal(error)
}
people = append(people, Person{
Name: line[0],
Address: &Address{
State: line[2],
City: line[3],
},
})
people[len(people)-1].Age,_ = strconv.Atoi(line[1])
}
peopleJson, _ := json.Marshal(people)
fmt.Println(string(peopleJson))
}
上面示例爲了簡化,都忽略了錯誤檢查。首先打開文件,然後通過緩衝讀取文件,循環讀每行,生成Person類型數組people,最後利用json.Marshal()
方法生成json。
運行上述示例,輸出結果爲:
[{"firstname":"Nic","lastname":"Raboy","address":{"city":"San Francisco","state":"CA"}},{"firstname":"Maria","lastname":"Raboy",
"address":{"city":"Dublin","state":"CA"}},{"firstname":"Steve","lastname":"","address":{"city":"","state":""}}]
3. 總結
本文介紹Golang加載csv文件並解析成數組。每次思緒中都會蹦出簡潔,確實Golang有點迷人。