doucitao2944 2018-04-09 08:55
浏览 248
已采纳

使用golang解析CSV文件中的嵌套JSON对象

I'm trying to parse a CSV file which contains a JSON object in the last column.
Here is an example with two rows from the input CSV file:

'id','value','createddate','attributes'
524256,CAFE,2018-04-06 16:41:01,{"Att1Numeric": 6, "Att2String": "abc"}
524257,BEBE,2018-04-06 17:00:00,{}

I tried using the parser from csv package:

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
}

But I got an error:

Error: line 2, column 0: wrong number of fields in line,

probably because the parser ignores the JSON scope which starts with {.

Should I be writing my own CSV parser, or is there a library that can handle this?

  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 vba代出现莫须有错误,都是一个个复制下来的为啥出错呢?
      • ¥15 /etc/vsftpd/vsftp.conf配置文件加了一行utf8_filesystem=YES之后,启动vsftpd报错
      • ¥15 W5100可以收广播,但是无法发出广播
      • ¥100 PCD点云排序和分割
      • ¥15 GG-CNN抓取数据集
      • ¥15 C++类和对象,多态性,继承,虚函数虚基类
      • ¥15 使用VS2019和Dev c++按%p输出地址,结果相差很大
      • ¥30 有偿解惑TINA老报错,求解惑
      • ¥15 arduino esp8266 编译问题
      • ¥15 metawrap画图报错