有谁知道如何编写一个将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
Run Code Online (Sandbox Code Playgroud)
并且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"]
]}
Run Code Online (Sandbox Code Playgroud)
Mic*_*ile 46
这在ruby 1.9中很容易,其中data是你的csv数据字符串
require 'csv'
require 'json'
CSV.parse(data).to_json
Run Code Online (Sandbox Code Playgroud)
Jos*_*lak 22
来自:
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
Run Code Online (Sandbox Code Playgroud)
至
[
{: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}
]
Run Code Online (Sandbox Code Playgroud)
做这个:
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}]
Run Code Online (Sandbox Code Playgroud)
图片来源:http://technicalpickles.com/posts/parsing-csv-with-ruby/
Mar*_*tuc 11
基于Josh的示例,您现在可以使用CSV :: table更进一步:
extracted_data = CSV.table('your/file.csv')
transformed_data = extracted_data.map { |row| row.to_hash }
Run Code Online (Sandbox Code Playgroud)
现在您可以立即调用to_json它,或者将其写入文件,格式很好:
File.open('your/file.json', 'w') do |file|
file.puts JSON.pretty_generate(transformed_data)
end
Run Code Online (Sandbox Code Playgroud)
小智 8
如果您在 Rails 项目中
CSV.parse(csv_string, {headers: true})
csv.map(&:to_h).to_json
Run Code Online (Sandbox Code Playgroud)