CSV到JSON Ruby脚本?

有谁知道如何编写一个Ruby脚本,将csv文件转换为json文件?

CSV将采用以下格式:

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 

和JSON需要导致这样的结果:

 { "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"] ]} 

这在Ruby 1.9中很容易,其中数据是您的csv数据string

  require 'csv' require 'json' CSV.parse(data).to_json 

从:

 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 

 [ {: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} ] 

做这个:

 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}] 

信用: http : //technicalpickles.com/posts/parsing-csv-with-ruby/

build立在Josh的例子上,你现在可以使用CSV :: table进一步:

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

现在你可以直接调用to_json来使用它,或者把它写到一个很好格式化的文件中:

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

如果你在一个Rails项目

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