2011-03-18 2 views
11

누구나 csv 파일을 json 파일로 변환하는 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"] 
]} 

답변

40

이 데이터가 CSV 데이터 문자열

이다 루비 1.9에서 쉽게
require 'csv' 
require 'json' 

CSV.parse(data).to_json 
+0

감사가 작동하지 않습니다 1.8에 대한 올바른 구문은 무엇입니까? – webbydevy

+0

이 보석 'fastercsv'를 설치하고 FasterCSV –

+0

에 CSV를 변경''데이터 File.open = ('경로///file.csv의') ( – benjineer

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

조쉬의 예제에, 당신은 지금이 걸릴 수 있습니다 한 단계 더 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 데이터를 할당 read'''. 'your/file.csv', header_converters : nil) camilizing 및 symbols로 변환하지 않고 헤더를 원래 문자열로 유지하려는 경우''' – benjineer

2

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