dte66654
2017-11-22 07:28
浏览 235
已采纳

无法使用golang读取csv文件中的json str

I export mysql data to a csv file, and there is one field use json string

when i use "encoding/csv" read this file, it show "wrong number of fields in line"

but when i delete the field, it's ok

like this: code example

is anyway to solve this?

图片转代码服务由CSDN问答提供 功能建议

我将mysql数据导出到一个csv文件中,并且有一个字段使用json字符串 \ n

当我使用“ encoding / csv”读取此文件时,它显示“行中的字段数错误”

,但是当我删除该字段时,就可以了

像这样: 代码示例

是否可以解决此问题?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duandu9260 2017-11-22 08:03
    已采纳

    You botched up quoting. To quote a " in CSV your preceed it with one more double quote (and not with backlashes):

    id,name
    42,"Henry Walton ""Indiana"" Jones Jr."
    
    已采纳该答案
    打赏 评论
  • dousi1970 2017-11-22 11:45

    Since what you ingesting is broken, you need to handle this manually. Catching error and putting record back in the format that you want.

    https://play.golang.org/p/82bfDGLwFd

    package main
    
    import (
        "encoding/csv"
        "fmt"
        "io"
        "strings"
    )
    
    func main() {
        csvReader := csv.NewReader(strings.NewReader(data))
        csvReader.LazyQuotes = true
        csvReader.Comma = ','
        csvReader.Comment = '#'
        for {
            row, err := csvReader.Read()
            if err == io.EOF {
                break
            }
            if err != nil {
    
                // checking here if the error you getting is what you experiencing 
                // due to json which is too many fields
                // checking for len(row) > 1 to avoid array index out of bound
                if e, ok := err.(*csv.ParseError); ok && e.Err == csv.ErrFieldCount && len(row) > 1 {
                    // we manually stitch it back to the expected format
                    row = []string{row[0], strings.Join(row[1:], "")}
    
                } else {
                    // some other type of error
                    fmt.Println(err)
                    continue
                }
            }
    
    
            for _, str := range row {
                fmt.Print(str, "\t")
            }
            fmt.Print("
    ")
        }
    }
    
    const data = `id,request_time
    129,"{\"request\":{\"protocol\":\"http\",\"method\":\"POST\",\"is_ajax\":false,\"query\":{\"signature\":\"\",\"timestamp\":\"1511107236\",\"nonce\":\"\",\"openid\":\"\",\"encrypt_type\":\"aes\"},\"url\":\"\",\"origin\":\"\",\"host\":\"\"},\"response\":{\"status\":200}}"
    `
    

    Have fun!

    打赏 评论

相关推荐 更多相似问题