Skip to content

Instantly share code, notes, and snippets.

@crm114
Created March 28, 2014 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crm114/9841741 to your computer and use it in GitHub Desktop.
Save crm114/9841741 to your computer and use it in GitHub Desktop.
CSV to JSON
#!/usr/bin/env ruby
# encoding UTF-8
require 'csv'
require 'json'
require 'open-uri'
# Check if we're working with an URL or filename
if ARGV[0].match(URI.regexp)
file = File.open(open(ARGV[0]))
else
file = File.open(ARGV[0])
end
# Set Variables
case ARGV[1]
when "comma"
col_sep = ","
when "tab"
col_sep = "\t"
else
col_sep = ","
end
output_filename = ARGV[2] || 'json.txt'
# Convert CSV to Hash
puts "Converting data"
csv_data = CSV.read(file, col_sep: col_sep)
headers = csv_data.shift.map {|i| i.to_s }
string_data = csv_data.map {|row| row.map {|cell| cell.to_s } }
csv_array_hash = string_data.map {|row| Hash[*headers.zip(row).flatten] }
# Write file
File.open(output_filename, 'w') {|f| f.write csv_array_hash.to_json}
puts "Created file with JSON at #{File.join(Dir.pwd, output_filename)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment