How can I parse a CSV string with JavaScript, which contains comma in data?

前端 未结 17 895
不知归路
不知归路 2020-11-22 01:52

I have the following type of string

var string = "\'string, duppi, du\', 23, lala"

I want to split the string into an array on each

17条回答
  •  长情又很酷
    2020-11-22 02:02

    I have also faced the same type of problem when I had to parse a CSV file.

    The file contains a column address which contains the ',' .

    After parsing that CSV file to JSON, I get mismatched mapping of the keys while converting it into a JSON file.

    I used Node.js for parsing the file and libraries like baby parse and csvtojson.

    Example of file -

    address,pincode
    foo,baar , 123456
    

    While I was parsing directly without using baby parse in JSON, I was getting:

    [{
     address: 'foo',
     pincode: 'baar',
     'field3': '123456'
    }]
    

    So I wrote code which removes the comma(,) with any other delimiter with every field:

    /*
     csvString(input) = "address, pincode\\nfoo, bar, 123456\\n"
     output = "address, pincode\\nfoo {YOUR DELIMITER} bar, 123455\\n"
    */
    const removeComma = function(csvString){
        let delimiter = '|'
        let Baby = require('babyparse')
        let arrRow = Baby.parse(csvString).data;
        /*
          arrRow = [
          [ 'address', 'pincode' ],
          [ 'foo, bar', '123456']
          ]
        */
        return arrRow.map((singleRow, index) => {
            //the data will include
            /*
            singleRow = [ 'address', 'pincode' ]
            */
            return singleRow.map(singleField => {
                //for removing the comma in the feild
                return singleField.split(',').join(delimiter)
            })
        }).reduce((acc, value, key) => {
            acc = acc +(Array.isArray(value) ?
             value.reduce((acc1, val)=> {
                acc1 = acc1+ val + ','
                return acc1
            }, '') : '') + '\n';
            return acc;
        },'')
    }

    The function returned can be passed into the csvtojson library and thus the result can be used.

    const csv = require('csvtojson')
    
    let csvString = "address, pincode\\nfoo, bar, 123456\\n"
    let jsonArray = []
    modifiedCsvString = removeComma(csvString)
    csv()
      .fromString(modifiedCsvString)
      .on('json', json => jsonArray.push(json))
      .on('end', () => {
        /* do any thing with the json Array */
      })

    Now you can get the output like:

    [{
      address: 'foo, bar',
      pincode: 123456
    }]
    

提交回复
热议问题