Skip to content

Instantly share code, notes, and snippets.

@bwicklund
Last active December 12, 2018 22:47
Show Gist options
  • Save bwicklund/66fe5f60525b29883a09 to your computer and use it in GitHub Desktop.
Save bwicklund/66fe5f60525b29883a09 to your computer and use it in GitHub Desktop.
Convert csv to json or ruby hash
require 'csv'
require 'json'
require 'pp'
if ARGV.length < 2
puts "usage: csv_to_struct.rb <in.csv> <out_name(no extension)> *[json|ruby] *symbolize_keys(bool)"
exit(1)
else
csv_file = ARGV[0]
output_file = ARGV[1].dup
# Safe for write
output_file.gsub!(/^.*(\\|\/)/, '')
output_file.gsub!(/[^0-9A-Za-z.\-]/, '_')
format = ARGV[2] || 'json'
symbolize_keys = ARGV[3] == 'true'
output_file << ( format == 'json' ? '.json' : '.rb' )
end
lines = CSV.open(csv_file).readlines
keys = lines.shift
if format != 'json' && symbolize_keys
keys.map!{ |k| k.to_sym }
end
File.open(output_file, 'w') do |f|
data = lines.map{ |values| Hash[keys.zip(values)]}
if format == 'json'
f.puts JSON.pretty_generate(data)
else
PP.pp(data,f)
end
end
@bwicklund
Copy link
Author

usage: csv_to_struct.rb <in.csv> <out_name(no extension)> *[json|ruby] *symbolize_keys(bool)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment