CSV to JSON Ruby Script?

To go from:

Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00

To

[
  {:year => 1997, :make => 'Ford', :model => 'E350', :description => 'ac, abs, moon', :price => 3000.00},
  {:year => 1999, :make => 'Chevy', :model => 'Venture "Extended Edition"', :description => nil, :price => 4900.00},
  {:year => 1999, :make => 'Chevy', :model => 'Venture "Extended Edition, Very Large"', :description => nil, :price => 5000.00},
  {:year => 1996, :make => 'Jeep', :model => 'Grand Cherokee', :description => "MUST SELL!\nair, moon roof, loaded", :price => 4799.00}
]

Do this:

csv = CSV.new(body, :headers => true, :header_converters => :symbol, :converters => :all)
csv.to_a.map {|row| row.to_hash }
#=> [{:year=>1997, :make=>"Ford", :model=>"E350", :description=>"ac, abs, moon", :price=>3000.0}, {:year=>1999, :make=>"Chevy", :model=>"Venture \"Extended Edition\"", :description=>"", :price=>4900.0}, {:year=>1999, :make=>"Chevy", :model=>"Venture \"Extended Edition, Very Large\"", :description=>nil, :price=>5000.0}, {:year=>1996, :make=>"Jeep", :model=>"Grand Cherokee", :description=>"MUST SELL!\nair, moon roof, loaded", :price=>4799.0}]

Credit: https://technicalpickles.com/posts/parsing-csv-with-ruby


Building on Josh's example, you can now take it one step further using CSV::table:

extracted_data   = CSV.table('your/file.csv')
transformed_data = extracted_data.map { |row| row.to_hash }

Now you can call to_json to use it right away, or write it down to a file, nicely formatted:

File.open('your/file.json', 'w') do |file|
  file.puts JSON.pretty_generate(transformed_data)
end

This is easy in ruby 1.9 where data is your csv data string

 require 'csv'
 require 'json'

 CSV.parse(data).to_json

If you're in a Rails project

CSV.parse(csv_string, {headers: true})
csv.map(&:to_h).to_json

Tags:

Ruby

Excel

Json