Skip to content

Instantly share code, notes, and snippets.

@ainoya
Created January 29, 2013 07:38
Show Gist options
  • Save ainoya/4662509 to your computer and use it in GitHub Desktop.
Save ainoya/4662509 to your computer and use it in GitHub Desktop.
Convert csv data to array of hash/yaml/json.etc.. in ruby
#!/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