Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing CSV string in ruby

Tags:

parsing

ruby

I have the following string - it's not exactly comma separated but has the same effect as a csv dataset:

response = "Date;Amount;Account;User\n2014-12-01;12.01;abcxyz;user1\n2014-12-01;10.09;fine;user2\n\r\n\t\t\r\n"

I tried running the following to parse it:

CSV.parse(response, :col_sep => ";", :row_sep => :auto) 

but I get the following error:

CSV::MalformedCSVError: Unquoted fields do not allow \r or \n

Any idea why this would be happening?

I also tried doing a response.gsub!("\t", "") to see if that was the issue, but it didn't seem to help.

like image 631
locoboy Avatar asked Dec 20 '14 07:12

locoboy


2 Answers

This will give you each row in an array.

CSV.parse( response.gsub( /[\r\t]/, '' ), col_sep: ";" )
=> [["Date", "Amount", "Account", "User"], ["2014-12-01", "12.01", "abcxyz", "user1"], ["2014-12-01", "10.09", "fine", "user2"], [], []]

Unless you want to merge all rows into a single line, you need to leave the \n for the parser to interpret as a new row.

like image 104
roob Avatar answered Oct 10 '22 01:10

roob


I got it work with the use of #strip :

require 'csv'

response = "Date;Amount;Account;User\n2014-12-01;12.01;abcxyz;user1\n2014-12-01;10.09;fine;user2\n\r\n\t\t\r\n"

CSV.parse(response.strip, :col_sep => ';') do |row|
  p row
end

output :

arup$ ruby a.rb
["Date", "Amount", "Account", "User"]
["2014-12-01", "12.01", "abcxyz", "user1"]
["2014-12-01", "10.09", "fine", "user2"]
like image 24
Arup Rakshit Avatar answered Oct 10 '22 00:10

Arup Rakshit