Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby CSV::Row remove new line

Tags:

ruby

csv

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
like image 337
Mark Meyer Avatar asked Mar 06 '14 02:03

Mark Meyer


2 Answers

Set the 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.

like image 150
Joshua Pinter Avatar answered Sep 21 '22 12:09

Joshua Pinter


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
like image 38
xdazz Avatar answered Sep 23 '22 12:09

xdazz