亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

npm 包 csvtojson CSV 解析錯誤:錯誤:unclosed_quote

npm 包 csvtojson CSV 解析錯誤:錯誤:unclosed_quote

米琪卡哇伊 2022-06-09 16:27:50
節點版本:v10.19.0npm 版本:6.13.4npm 包 csvtojson包鏈接csvtojson({ "delimiter": ";", "fork": true}).fromStream(fileReadStream).subscribe((dataObj) => {console.log(dataObj);}, (err) => {console.error(err);}, (success) => {console.log(success);});在嘗試處理大型 CSV 文件(大約 130 萬條記錄)時,在成功處理某些記錄(例如 400 多條記錄之后)后,我遇到了錯誤“ CSV Parse Error: Error: unclosed_quote. ”。從 CSV 文件中,我看不到那里的數據格式有任何問題,但是解析器可能會引發此錯誤,因為在列/字段值中發現了“\n”字符。此軟件包是否已有可用的解決方案?或者有解決此錯誤的解決方法嗎?或者有沒有辦法跳過這樣的 CSV 行,而不僅僅是這個錯誤,讓整個 CSV 到 JSON 解析工作而不會卡???任何幫助都感激不盡。
查看完整描述

2 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

我已經玩過這個,并且可以使用 CSV 文件行掛鉤csv-file-line-hook來掛鉤,您可以檢查無效行并修復或簡單地使它們無效。


下面的示例將簡單地跳過無效行(缺少結束引號)


例子.js


const fs = require("fs");


let fileReadStream = fs.createReadStream("test.csv");

let invalidLineCount = 0;


const csvtojson = require("csvtojson");

csvtojson({ "delimiter": ";", "fork": true })

.preFileLine((fileLineString, lineIdx)=> {

    let invalidLinePattern = /^['"].*[^"'];/;

    if (invalidLinePattern.test(fileLineString)) {

        console.log(`Line #${lineIdx + 1} is invalid, skipping:`, fileLineString);

        fileLineString = "";

        invalidLineCount++;

    }

    return fileLineString

})

.fromStream(fileReadStream) 

.subscribe((dataObj) => { 

    console.log(dataObj);

}, 

(err) => { 

    console.error("Error:", err); 

}, 

(success) => {

    console.log("Skipped lines:", invalidLineCount);

    console.log("Success"); 

});

測試.csv


Name;Age;Profession

Bob;34;"Sales,Marketing"

Sarah;31;"Software Engineer"

James;45;Driver

"Billy, ;35;Manager

"Timothy;23;"QA


查看完整回答
反對 回復 2022-06-09
?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

這個正則表達式效果更好


/^(?:[^"\]|\.|"(?:\.|[^"\])")$/g


這是通過讀取每一行來處理大文件的更復雜的工作腳本


import csv from 'csvtojson'

import fs from 'fs-extra'

import lineReader from 'line-reader'


import { __dirname } from '../../../utils.js'


const CSV2JSON = async(dumb, editDumb, headers, {

    options = {

        trim: true,

        delimiter: '|',

        quote: '"',

        escape: '"',

        fork: true,

        headers: headers

    }

} = {}) => {

    try {

        log(`\n\nStarting CSV2JSON - Current directory: ${__dirname()} - Please wait..`)


        await new Promise((resolve, reject) => {

            let firstLine, counter = 0

            lineReader.eachLine(dumb, async(line, last) => {

                counter++


                // log(`line before convert: ${line}`)

                let json = (

                    await csv(options).fromString(headers + '\n\r' + line)

                        .preFileLine((fileLineString, lineIdx) => {

                            // if it its not the first line

                                // eslint-disable-next-line max-len

                                if (counter !== 1 && !fileLineString.match(/^(?:[^"\\]|\\.|"(?:\\.|[^"\\])*")*$/g)) {

                                    // eslint-disable-next-line max-len

                                    console.log(`Line #${lineIdx + 1} is invalid. It has unescaped quotes. We will skip this line.. Invalid Line: ${fileLineString}`)

                                    fileLineString = ''

                                }


                            return fileLineString

                        })

                        .on('error', e => {

                            e = `Error while converting CSV to JSON.

                            Line before convert: ${line}

                            Error: ${e}`

                            throw new BaseError(e)

                        })

                )[0]


                // log(`line after convert: ${json}`)


                if (json) {

                    json = JSON.stringify(json).replace(/\\"/g, '')


                    if (json.match(/^(?:[^"\\]|\\.|"(?:\\.|[^"\\])*")*$/g)) {

                        await fs.appendFile(editDumb, json)

                    }

                }


                if (last) {

                    resolve()

                }

            })

        })

    } catch (e) {

        throw new BaseError(`Error while converting CSV to JSON - Error: ${e}`)

    }

}


export { CSV2JSON }



查看完整回答
反對 回復 2022-06-09
  • 2 回答
  • 0 關注
  • 267 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號