Created
March 28, 2014 19:56
-
-
Save crm114/9841741 to your computer and use it in GitHub Desktop.
CSV to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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