不能用golang在csv文件中读取json str

时间:2017-11-22 07:28:59

标签: csv go

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

当我使用" encoding / csv"阅读此文件,它显示"行#34;

中的字段数错误

但是当我删除该字段时,它没问题

像这样: code example

无论如何要解决这个问题?

2 个答案:

答案 0 :(得分:2)

你搞砸了。 要在CSV中引用",请在其前面添加一个双引号(而不是反斜杠):

id,name
42,"Henry Walton ""Indiana"" Jones Jr."

答案 1 :(得分:0)

由于您提取的内容已损坏,您需要手动处理。捕获错误并将记录恢复为您想要的格式。

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("\n")
    }
}

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}}"
`

玩得开心!