Golang解析CSV檔案

2021-10-06 06:06:47 字數 1054 閱讀 4392

日常工作實用csv型別檔案很普遍,而且很容易從其他資料來源中獲得。如google sheets,microsoft excel,或關係型資料庫。如何在應用中載入並解析csv呢,本文帶你實用golang解析csv檔案。

通常其他語言處理csv檔案比較麻煩,通常需要通過第三方庫,解析工作量較大。golang中內建了encoding/csv包,讓解析工作變得很簡單。

假設我們的資料結構為:姓名、年齡、省份、城市

張勇,24,江蘇,南京

李婉,23,山東,濟南

張飛,33,,

上面資料表示一組人資訊。包括多行、列,我們的任務是載入資料並生成json型別資料。

package main

import (

"bufio"

"encoding/csv"

"encoding/json"

"fmt"

"io"

"log"

"os"

"strconv"

)type person struct

type address struct

func main() else if error != nil

name: line[0],

address: &address,

})people[len(people)-1].age,_ = strconv.atoi(line[1])

} peoplejson, _ := json.marshal(people)

fmt.println(string(peoplejson))

}

上面示例為了簡化,都忽略了錯誤檢查。首先開啟檔案,然後通過緩衝讀取檔案,迴圈讀每行,生成person型別陣列people,最後利用json.marshal()方法生成json。

執行上述示例,輸出結果為:

[},},}]
本文介紹golang載入csv檔案並解析成陣列。每次思緒中都會蹦出簡潔,確實golang有點迷人。

golang 解析csv檔案到struct

2019獨角獸企業重金招聘python工程師標準 預設情況下,csv檔案的首行會被當作header處理。file.csv hosname,ip redis,172.17.0.2 mariadb,172.17.0.3 go type info struct struct slice infos inf...

解析csv檔案

以下內容僅為記錄 第一步 解析csv檔案 test public void testcsv throws exception catch filenotfoundexception e string line string everyline try system.out.println csv 中...

CSV檔案解析

實現功能 針對讀取的csv文件字串進行map格式輸出 主要 如下 public class csvpaser extends parser public static void main string args system.out.println map 說明 該部分主要針對多條記錄做相應的解析 ...