2011-03-18 62 views
11

有誰知道如何編寫一個將csv文件轉換爲json文件的Ruby腳本?CSV到JSON Ruby腳本?

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

回答

40

這是很容易在Ruby 1.9的,其中數據是你的CSV數據串

require 'csv' 
require 'json' 

CSV.parse(data).to_json 
+0

感謝不起作用爲1.8,我無法升級 - 1.87的正確語法是什麼? – webbydevy 2011-03-22 04:12:39

+0

安裝gem'fastercsv'並將CSV更改爲FasterCSV – 2011-03-22 19:51:57

+0

'''data = File.open('/ path/to/file.csv')。read'''指定數據 – benjineer 2017-10-15 10:33:52

16

如果要從:

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/

7

上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 
+0

'''extracted_data = CSV.table( 'your/file.csv',header_converters:nil)'''如果你想把標題保留爲原始字符串,而不是駝峯化並轉換爲符號 – benjineer 2017-10-15 10:41:58

2

如果你在Rails項目是

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