I am opening a CSV file and then converting it to JSON. This is all working fine except the JSON data has \n
characters in the string. These are not part of the last element as far as I can tell from printing it and trying to chomp it. When I print the row
it does have \n
require 'csv'
require 'json'
def csv_to_json (tmpfile)
JSON_ARRAY = Array.new
CSV.foreach(tmpfile) do |row|
print row[row.length - 1]
if row[row.length - 1].chomp! == nil
print row
end
JSON_ARRAY.push(row)
end
return JSON_ARRAY.to_json
end
The JSON then looks like this when it is returned
["field11,field12\n",
"field21,field22\n"]
How can I remove these new line characters?
EDIT:
These are CSV::Row
objects and do not support string operations like chomp
or strip
tmpfile
is in the format
field11,field21
field21,field22
row_sep
to nil
.JSON_ARRAY.push( row.to_s( row_sep: nil ) )
or
JSON_ARRAY.push( row.to_csv( row_sep: nil ) )
As a comment pointed out, CSV::row#to_s
is an alias for CSV::row#to_csv
, which adds a row separator after each line automatically. To get around this you can just set the row_sep
to nil
and it will not add \n
at the end of each row.
Hope that helps.
The simplest way:
File.read(tmpfile).split("\n")
By the way, if you want to remove the newline from the string, you could use String::strip
method.
CSV.foreach(tmpfile) do |row|
# here row should be an array.
p row
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With