日常工作实用CSV类型文件很普遍,而且很容易从其他数据源中获得。如Google Sheets,Microsoft Excel,或关系型数据库。如何在应用中加载并解析CSV呢,本文带你实用Golang解析csv文件。
1. 概述
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))
}
json.Marshal()
运行上述示例,输出结果为:
[{"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有点迷人。