Skip to content

Instantly share code, notes, and snippets.

@enriclluelles
Created December 2, 2011 16:52
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save enriclluelles/1423950 to your computer and use it in GitHub Desktop.
Save enriclluelles/1423950 to your computer and use it in GitHub Desktop.
CSV to JSON
#!/usr/bin/env ruby
require 'csv'
require 'json'
if ARGV.size != 2
puts 'Usage: csv_to_json input_file.csv output_file.json'
puts 'This script uses the first line of the csv file as the keys for the JSON properties of the objects'
exit(1)
end
lines = CSV.open(ARGV[0]).readlines
keys = lines.delete lines.first
File.open(ARGV[1], 'w') do |f|
data = lines.map do |values|
Hash[keys.zip(values)]
end
f.puts JSON.pretty_generate(data)
end
@mmcdaris
Copy link

Thanks for this one! Worked great. 👍

@yassinagx
Copy link

Thanks

@pjmartorell
Copy link

lines = CSV.open(ARGV[0], headers: true)
File.open(ARGV[1], 'w') do |f|
  data = lines.map(&:to_h)
  f.puts JSON.pretty_generate(data)
end

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