【问题标题】:Parsing nested JSON objects in a CSV file with golang使用 golang 解析 CSV 文件中的嵌套 JSON 对象
【发布时间】:2018-04-09 08:55:16
【问题描述】:

我正在尝试解析最后一列中包含 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
}

但我得到一个错误:

错误:第 2 行,第 0 列:行中的字段数错误,

可能是因为解析器忽略了以{ 开头的 JSON 范围。

我应该编写自己的 CSV 解析器,还是有可以处理这个的库?

【问题讨论】:

  • 请发布您尝试过的内容。

标签: json csv parsing go


【解决方案1】:

您的 CSV 输入不遵循正常的 CSV 约定,使用不带引号的字段(对于 JSON)。

我认为最好的方法是在 Go 程序或外部脚本中预处理您的输入。

如果您的 CSV 输入是可预测的(如您的问题中所示),则应该很容易正确引用最后一个元素,例如,在将其传递给 CSV 解析器之前使用简单的 strings.Split 调用。

【讨论】:

  • 我怀疑对文件进行预处理会很困难,因为输入文件(可能很大)是通过网络到达的,并且在传入时正在处理(通知multipart.Part)。
  • 一点也不。只需创建一个io.Reader 包装器,它会读取每一行,调用strings.SplitN(input, 4),正确引用/转义最后一个字段,然后将修改后的行作为输出写入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
相关资源
最近更新 更多