Created
May 3, 2019 06:08
-
-
Save Zejnilovic/6f37ab8d0b8bdfc08171af0f79e3ca17 to your computer and use it in GitHub Desktop.
Convert 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
require 'json' | |
require 'csv' | |
# Transforms CSV into JSON and saves it next to the CSV. | |
# Paths to CSV accepted as an input argument | |
csv_in = ARGV[0] | |
ARGV.clear | |
while true | |
break if !csv_in.nil? && File.exist?(csv_in) | |
puts 'Give me path to CSV' | |
csv_in = gets.chomp | |
end | |
puts "Starting" | |
raw_csv = CSV.read(csv_in, encoding: 'UTF-8') | |
header = raw_csv.shift.collect(&:to_sym) | |
json_data = raw_csv.map { |a| Hash[header.zip(a)] } | |
File.open(json_out.gsub('.csv', '.json'), 'w') do |f| | |
f.write(JSON.pretty_generate(json_data)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment