我正在尝试解析最后一列中包含 JSON 对象的 CSV 文件。
这是一个包含输入 CSV 文件中的两行的示例:
'id','value','createddate','attributes'
524256,CAFE,2018-04-06 16:41:01,{"Att1Numeric": 6, "Att2String": "abc"}
524257,BEBE,2018-04-06 17:00:00,{}
我尝试使用 csv
包中的解析器:
func processFileAsCSV(f *multipart.Part) (int, error) {
reader := csv.NewReader(f)
reader.LazyQuotes = true
reader.Comma = ','
lineCount := 0
for {
line, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
fmt.Println("Error:", err)
return 0, err
}
if lineCount%100000 == 0 {
fmt.Println(lineCount)
}
lineCount++
fmt.Println(lineCount, line)
processLine(line) // do something with the line
}
fmt.Println("done!", lineCount)
return lineCount, nil
}
但是我得到一个错误:
Error: line 2, column 0: wrong number of fields in line,
可能是因为解析器忽略了以 {
开头的 JSON 范围。
我应该编写自己的 CSV 解析器,还是有可以处理此问题的库?
最佳答案
您的 CSV 输入不遵循正常的 CSV 约定,使用不带引号的字段(对于 JSON)。
我认为最好的方法是在您的 Go 程序或外部脚本中预处理您的输入。
如果您的 CSV 输入是可预测的(如您的问题中所示),则应该很容易正确引用最后一个元素,例如,在将其传递给CSV 解析器。
关于json - 使用 golang 解析 CSV 文件中的嵌套 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49729041/