Created
January 29, 2013 07:38
-
-
Save ainoya/4662509 to your computer and use it in GitHub Desktop.
Convert csv data to array of hash/yaml/json.etc.. in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'csv' | |
require 'yaml' | |
require 'json' | |
csv =<<EOF | |
id,name,price | |
A1,apple,100 | |
A2,grape,300 | |
A3,orange,150 | |
EOF | |
data=CSV.parse(csv) | |
puts data.drop(1).each_with_object([]){|rows,obj| obj << Hash[data.first.zip rows]}.to_yaml # you can use to_json,etc ... instead of to_yaml if you want | |
# It puts : | |
#- id: A1 | |
# name: apple | |
# price: '100' | |
#- id: A2 | |
# name: grape | |
# price: '300' | |
#- id: A3 | |
# name: orange | |
# price: '150' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment