Skip to content

Instantly share code, notes, and snippets.

@Loddan
Forked from enriclluelles/csv_to_json.rb
Last active December 29, 2015 10:29
Show Gist options
  • Save Loddan/7657245 to your computer and use it in GitHub Desktop.
Save Loddan/7657245 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'csv'
require 'json'
if ARGV.size != 2
puts 'Usage: csv_to_json in out'
puts
puts ' input: Input CSV file'
puts ' out: Output JSON file or -- for stdout'
puts
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
data = lines.map do |values|
Hash[keys.zip(values)]
end
STDOUT.reopen(File.open(ARGV[1], 'w')) unless ARGV[1].eql?('--')
puts JSON.pretty_generate(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment