【发布时间】:2018-11-11 17:42:00
【问题描述】:
我正在创建一个可以获取 JSON 文件的工具,然后使用 Go 从中创建一个 PDF
这是我的 JSON 示例:
[{"Name":"Ollie","Age":"25","Comment":"This is my comment"},{"Name":"Amy","Age":"28","Comment":"Another comment"},{"Name":"Joey","Age":"19","Comment":"Comment from Joey"},{"Name":"James","Age":"23","Comment":"James' comment"},{"Name":"Richard","Age":"20","Comment":"Richard has also made 24"}]
我有一些可以使用 CSV 文件的东西,但现在我也希望能够获取 JSON 文件
我用来创建 PDF 的包是 gofpdf
其中一个问题是我需要将 JSON 传递给一个结构来读取它,该结构有它自己的自定义类型 - 因为我使用的是自定义类型,所以我无法将值传递到 gofpdf 的函数中制作PDF
我只是希望能够将我的结构(声明为字符串)中的值作为函数中的字符串传递:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"time"
"github.com/jung-kurt/gofpdf"
)
这是我的结构:
type Person struct {
Name string `json:"Name"`
Age string `json:"Age"`
Comment string `json:"Comment"`
}
func main() {
data, err := ioutil.ReadFile("csv-to-json.json")
if err != nil {
fmt.Println(err)
}
//create variable people which is array of Person structs
var People []Person
//Take the data object (json file) and place into the People array of struct
json.Unmarshal(data, &People)
fmt.Println(People[:])
pdf := NewReport()
pdf = CreateTableJSON(pdf, People[:])
if pdf.Err() {
log.Fatalf("Failed creating PDF report: %s\n", pdf.Error())
}
err = SavePDFJSON(pdf)
if err != nil {
log.Fatalf("Cannot save PDF: %s|n", err)
}
}
func CreateTableJSON(pdf *gofpdf.Fpdf, table []Person) *gofpdf.Fpdf {
for _, str := range table {
下面是我苦苦挣扎的地方。 str 需要是字符串类型
pdf.CellFormat(20, 7, str, "1", 0, "C", false, 0, "")
pdf.Ln(-1)
}
return pdf
}
//Create function that generates a new pdf report
func NewReport() *gofpdf.Fpdf {
pdf := gofpdf.New("P", "mm", "Letter", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 28)
pdf.Cell(40, 10, "My title for the PDF (New)!")
pdf.Ln(12)
pdf.SetFont("Arial", "", 11)
pdf.Cell(40, 10, time.Now().Format("Mon Jan 2, 2006"))
pdf.Ln(12)
return pdf
}
func SavePDFJSON(pdf *gofpdf.Fpdf) error {
return pdf.OutputFileAndClose("pdf_from_json.pdf")
}
所以我能够从 JSON 文件中读取数据并将这些行打印到控制台,但我不能在 PDF 生成函数中使用这些数据,因为我必须创建自定义类型,并且函数参数需要字符串。有谁可以帮我离开这里吗?我想要这个的等价物:
pdf.CellFormat(20, 7, **TOSTRING(str)**, "1", 0, "C", false, 0, "")
我已经玩了大约 3 个小时了,没有任何运气
提前致谢
【问题讨论】:
标签: json go type-conversion