使用插件json2csv
- 在使用过程中遇到JSON转CSV格式问题,解析内嵌式数据结构是一件非常头疼的事,就找到了一个自动解析的库
- 仓库地址:https://github.com/jehiah/json2csv
results, err := json2csv.JSON2CSV(data)
if err != nil {
log.Fatal(err)
}
if len(results) == 0 {
return
}
bytesBuffer := &bytes.Buffer{}
bytesBuffer.WriteString("\xEF\xBB\xBF")
err = printCSV(bytesBuffer, results)
if err != nil {
log.Fatal(err)
}
c.Writer.Header().Set("Content-Disposition", "attachment;filename=test.csv")
c.Data(http.StatusOK, "text/csv", bytesBuffer.Bytes())
func printCSV(w io.Writer, results []json2csv.KeyValue) error {
csv := json2csv.NewCSVWriter(w)
if err := csv.WriteCSV(results); err != nil {
return err
}
return nil
}