go语言中将CSV文件数据转换为JSON格式并保存到文件
需求:将CSV数据转换为JSON格式数据文件,或将其流式传输出来......就像一个 http 服务
data.csv数据文件:
Adam,36,CEO
Eve,34,CFO
Mike,38,COO
输出到data.json文件 数据格式:
[
{"Name":"Adam","Age":36,"Job":"CEO"},
{"Name":"Eve","Age":34,"Job":"CFO"},
{"Name":"Mike","Age":38,"Job":"COO"}
]
代码示例:
package controllers
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"strconv"
"time"
"os"
)
// TestController is a test control
type TestController struct {
//beego.Controller
BaseController
}
type Employee struct {
Name string
Age int
Job string
}
func (c *TestController) Csv2json() {
c.Ctx.WriteString(`csv2json`)
//从CSV文件中读取数据
csvFile, err := os.Open("logs/data.csv")
if err != nil {
fmt.Println(err)
}
defer csvFile.Close()
reader := csv.NewReader(csvFile)
reader.FieldsPerRecord = -1
csvData, err := reader.ReadAll()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var oneRecord Employee
var allRecords []Employee
for _, each := range csvData {
oneRecord.Name = each[0]
oneRecord.Age, _ = strconv.Atoi(each[1]) //需要将整数转换为字符串
oneRecord.Job = each[2]
allRecords = append(allRecords, oneRecord)
}
//转换为 JSON
jsondata, err := json.Marshal(allRecords)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// 注意:您也可以将 JSON 数据流式传输到 http 服务,而不是保存到文件
fmt.Println(string(jsondata))
//现在写入JSON文件
jsonFile, err := os.Create("logs/data.json")
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
jsonFile.Write(jsondata)
jsonFile.Close()
}
效果:
相关文章