CSV到JSON Ruby脚本?
有人知道如何编写一个Ruby脚本,将csv文件转换成json文件吗 CSV将采用以下格式:CSV到JSON Ruby脚本?,ruby,json,excel,Ruby,Json,Excel,有人知道如何编写一个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 (lock
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数据字符串
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
到
这样做:
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}]
信用证:以Josh的例子为基础,您现在可以进一步使用: 现在,您可以调用
以立即使用它,或者将其写入格式良好的文件:
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
我的解决方案就是这样结束的,与Mariu的非常相似
require 'csv'
require 'json'
csv_table = CSV.parse(File.read('data.csv'), headers: true)
json_string = csv_table.map(&:to_h).to_json
File.open('data.json','w') do |f|
f.puts(json_string)
end
感谢1.8不起作用,我无法升级-1.87的正确语法是什么?安装gem'fastercsv'并将CSV更改为fastercsvdata=File.open('/path/to/File.CSV')。读取
分配数据提取的数据=CSV.table('your/File.CSV',header\u converters:nil)
如果要将头保留为原始字符串,在普通Ruby中,Ruby-e“需要'csv';需要'json'”-e将csv.parse(File.open(ARGV[0]),{headers:true}.map(&:to_h).to_json“example.csv
CSV.parse(csv_string, {headers: true})
csv.map(&:to_h).to_json
require 'csv'
require 'json'
csv_table = CSV.parse(File.read('data.csv'), headers: true)
json_string = csv_table.map(&:to_h).to_json
File.open('data.json','w') do |f|
f.puts(json_string)
end