Does anyone know how to write a Ruby script that would convert a csv file to a json file?
The CSV would be in this format:
Canon,Digital IXUS 70,"Epic, Epic 100",3x,Yes (lockable),Yes (lockable),Yes
Canon, Digital IXUS 75,"Epic, Epic 100",3x,Yes (lockable),Yes (lockable),Yes
Canon,Digital IXUS 80,"Epic, Epic 100",3x,Yes (lockable),Yes (lockable),Yes
and the JSON would need to result in this:
{ "aaData": [
[ "Canon" , "Digital IXUS 70" , "3x" , "Yes (lockable)" , "Yes (lockable)" , "Yes"],
[ "Canon" , "Digital IXUS 75" , "3x" , "Yes (lockable)" , "Yes (lockable)" , "Yes"],
[ "Canon" , "Digital IXUS 80" , "3x" , "Yes (lockable)" , "Yes (lockable)" , "Yes"]
]}
This is easy in ruby 1.9 where data is your csv data string
require 'csv'
require 'json'
CSV.parse(data).to_json
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
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