Skip to content

Instantly share code, notes, and snippets.

@Zejnilovic
Created May 3, 2019 06:08
Show Gist options
  • Save Zejnilovic/6f37ab8d0b8bdfc08171af0f79e3ca17 to your computer and use it in GitHub Desktop.
Save Zejnilovic/6f37ab8d0b8bdfc08171af0f79e3ca17 to your computer and use it in GitHub Desktop.
Convert CSV to JSON
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